shell - 对 exec 重定向到 /dev/null 感到困惑,我做得对吗?
问题描述
背景
我正在用POSIX shell 脚本训练自己,请在回答时避免任何Bashism。谢谢你。
感谢Kusalananda的回答,我现在知道如何确定我的脚本是否以交互方式运行,即它何时连接到stdin
.
问题
由于我很少使用exec
(手册页),我不确定我是否正确地执行以下想法?请详细说明。
如果脚本正在运行:
交互方式:将错误消息输出到
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
...
}
推荐阅读
- asp.net-mvc - 为什么asp.net mvc在项目中不包含图片上传的文件夹?
- flutter - 受异常影响的后台任务
- python - 根据 Python 中的先前选择更改下拉选项 ipywidgets
- python-3.x - “str”对象在 BeautifulSoup4 中没有属性“文本”
- python - 在 python/pygame 中射击坦克子弹
- javascript - 以间隔将数据从 Django API 推送到 Mixed Chart.js
- amazon-web-services - 在 Jenkins 的 docker 容器中运行命令
- xml - 元素类型必须后跟属性规范、“>”或“/>”
- javascript - HTML/Javascript 上传后如何在 Web 应用程序上显示图像?
- javascript - 如何生成随机素数?