我正在训练自己使用POSIX shell脚本,请在回答时避免使用任何Bashism。谢谢。
由于Kusalananda的answer,我现在知道如何确定脚本是否以交互方式运行,即何时将其连接到stdin
。
由于我很少使用exec
(man page),因此不确定我是否正确地执行了以下想法?请详细说明。
如果脚本正在运行:
交互式:将错误消息输出到stderr
,否则将在默认环境设置中运行。
非交互式地:在此示例中,将所有输出重定向到/dev/null
(最后,我可能会希望重定向{{1} }和stdout
转换为实际文件)。
stderr
答案 0 :(得分:0)
看来我已经接近了。由于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
...
}