我正在训练自己在POSIX shell脚本,请回答时避免任何Bashism。谢谢。
我现在知道了,感谢Kusalananda的answer,如何确定我的脚本是否以交互方式运行,即它是否连接到stdin
。
由于我很少使用exec
(man page),我不确定我是否正确地做了以下想法?请详细说明。
如果脚本正在运行:
stderr
,否则在默认环境设置中运行。/dev/null
(最后我可能希望将stdout
和stderr
重定向到实际文件)。# test if file descriptor 0 = standard input is connected to the terminal
running_interactively () { [ -t 0 ]; }
# if not running interactively, then redirect all output from this script to the black hole
! running_interactively && exec > /dev/null 2>&1
print_error_and_exit ()
{
# if running interactively, then redirect all output from this function to standard error stream
running_interactively && exec >&2
...
}
看来我很亲密。由于running_interactively
函数按预期工作,我能够继续重定向到文件,如下所示。
我编辑了这个答案,以便有更多的代码可以重复使用。
#!/bin/sh
is_running_interactively ()
# test if file descriptor 0 = standard input is connected to the terminal
{
# test if stdin is connected
[ -t 0 ]
}
redirect_output_to_files ()
# redirect stdout and stderr
# - from this script as a whole
# - to the specified files;
# these are located in the script's directory
{
# get the path to the script
script_dir=$( dirname "${0}" )
# redirect stdout and stderr to separate files
exec >> "${script_dir}"/stdout \
2>> "${script_dir}"/stderr
}
is_running_interactively ||
# if not running interactively, add a new line along with a date timestamp
# before any other output as we are adding the output to both logs
{
redirect_output_to_files
printf '\n'; printf '\n' >&2
date; date >&2
}
print_error_and_exit ()
{
# if running interactively redirect all output from this function to stderr
is_running_interactively && exec >&2
...
}