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

问题描述 投票:1回答:2

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

  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正在被调用。

bash shell
2个回答
2
投票

-t标志检查是否有任何标准文件描述符是打开的,特别是[ -t 1 ]将表示STDOUT是否附加到tty,因此当从终端运行时,它将始终将此条件断言为true。

此外,return关键字仅在运行函数以突破它而不是终止shell本身时才适用。由于在从脚本运行时命中exit 1而终止窗口关闭的声明只有在你使用source脚本时才会发生(即在同一个shell中),如果在子shell中执行脚本则不会发生。

只需在if条件中执行:,就可以在脚本中使用构造进行无操作

if [[ -t 1 ]]; then
    # if we are in a terminal just return, do not exit.
    :

此外-t由POSIX定义,因为你可以做[ -t 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;

}

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

© www.soinside.com 2019 - 2024. All rights reserved.