Bash 检查脚本是否已重定向

Bash 检查脚本是否已重定向,bash,shell,io-redirection,Bash,Shell,Io Redirection,我有一个bash脚本,如果输出显示在终端中,或者如果它被重定向到一个文件,那么它必须以不同的方式运行。它必须执行以下操作(myscript.sh): 这将被称为: ./myscript.sh ./myscript.sh > /tmp/log.txt if [[ -t 1 ]]; then # console is attached else # Redirected to somewhere fi 或者像这样: ./myscript.sh ./myscript.sh >

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

这将被称为:

./myscript.sh
./myscript.sh > /tmp/log.txt
if [[ -t 1 ]]; then
 # console is attached
else 
 # Redirected to somewhere
fi
或者像这样:

./myscript.sh
./myscript.sh > /tmp/log.txt
if [[ -t 1 ]]; then
 # console is attached
else 
 # Redirected to somewhere
fi

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

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

 -t fd  True if file descriptor fd is open and refers to a terminal.
检查如下:

./myscript.sh
./myscript.sh > /tmp/log.txt
if [[ -t 1 ]]; then
 # console is attached
else 
 # Redirected to somewhere
fi