bash - 检查脚本是否已被重定向

标签 bash shell io-redirection

我有一个 bash 脚本,如果输出显示在终端中,或者如果它被重定向到一个文件,它必须以不同的方式运行。它必须做这样的事情(myscript.sh):

if [ redirected_to_terminal ] ; then
    flag="--color"
else
    flag="--no-color"
fi

grunt $flag

这会被这样调用:

./myscript.sh

或者像这样:

./myscript.sh > /tmp/log.txt

stdout 的重定向将在脚本中检测到。这可能吗?

最佳答案

你可以使用 bash 的 -t 选项:

 -t fd  True if file descriptor fd is open and refers to a terminal.

然后像这样检查:

if [[ -t 1 ]]; then
 # console is attached
else 
 # Redirected to somewhere
fi

关于bash - 检查脚本是否已被重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16033221/

相关文章:

linux - 将错误重定向到一个文件,将标准输出重定向到另一个函数,然后再重定向到另一个文件

linux - 检查 Linux text/fb 控制台当前是否按住 shift 键

bash - 如何使用函数以正确的方式退出 shell 脚本

bash - 这些流重定向如何工作?

bash - 为什么 sed replace + redirect 删除了我的文件?

java - 为什么有些命令在 Unix 上需要锁而其他命令则不需要?

bash - 是否可以在 bash 中使用连续的或运算符?

bash - 多行输出到带分隔符字符串的单行连接

linux - 如何在删除前检查文件是否存在?

java - 从clearcase动态 View 下载文件