如果在脚本中退出,则在使用终端/ tty时不要退出

时间:2018-03-02 06:20:34

标签: bash shell

如果用户在终端中输入命令,我想回显错误声明,但我不希望终端关闭,所以我有这个:

  if [[ "$fle" =~ [^a-zA-Z0-9] ]]; then
    echo "quicklock: lockname has invalid chars - must be alpha-numeric chars only."
    if [[ -t 1 ]]; then
        # if we are in a terminal just return, do not exit.
        return 1;
    else
        exit 1;
    fi
  fi

然而if [[ -t 1 ]]; then似乎不起作用,我正在使用的终端窗口立即关闭,所以我认为正在调用exit 1

2 个答案:

答案 0 :(得分:2)

-t标志检查是否有任何标准文件描述符是打开的,具体来说[ -t 1 ]将表示STDOUT是否附加到tty,所以当从终端运行时,它将始终断言这个条件为真。

return关键字仅在运行函数时才适用,而不是终止shell本身。由于从脚本运行时命中exit 1而导致终端窗口关闭的声明只有在您source脚本(即在同一个shell中)时才会发生,并且如果您在执行脚本时不会发生子壳。

只需在if条件中执行:

,就可以在脚本中使用构造来执行无操作
if [[ -t 1 ]]; then
    # if we are in a terminal just return, do not exit.
    :

此外,-t由POSIX定义,因此您可以[ -t 1 ]执行此操作。

答案 1 :(得分:0)

这实际上是最终为我工作的:

function on_conditional_exit {

   if [[ $- == *i* ]]; then
       # if we are in a terminal just return, do not exit.
      echo -e "quicklock: since we are in a terminal, not exiting.";
      return 0;
   fi

   echo -e "quicklock: since we are not in a terminal, we are exiting...";
   exit 1;

}

测试是看我们是在终端还是在某个地方的脚本......如果我们是互动的,我们就在终端..