如果用户在终端中输入命令,我想回显错误语句,但我不希望终端关闭,所以我有:
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
正在被调用。
-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 ]
。
这实际上是最终为我工作的:
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;
}
测试是看我们是在终端还是在某个地方的脚本...如果我们是互动的,我们在一个终端..