我想做这种形式的事情:
one() {
redirect_stderr_to '/tmp/file_one'
# function commands
}
two() {
redirect_stderr_to '/tmp/file_two'
# function commands
}
one
two
这将连续运行 one
和 two
,将 stderr
重定向到相应的文件。等效的工作是:
one() {
# function commands
}
two() {
# function commands
}
one 2> '/tmp/file_one'
two 2> '/tmp/file_two'
但这有点丑陋。我宁愿将所有重定向指令都放在函数本身中。会更容易管理。我觉得这可能不可能,但想确定一下。
最佳答案
最简单和最可靠的方法是使用函数级重定向:注意重定向命令是如何应用于整个函数,在下面的结束 }
之后,作用于每个函数(无需重置):
# Define functions with redirected stderr streams.
one() {
# Write something to stderr:
echo one >&2
} 2> '/tmp/file_one'
two() {
# Write something to stderr:
echo two >&2
} 2> '/tmp/file_two'
one
two
# Since the function-level redirections are localized to each function,
# this will again print to the terminal.
echo "done" >&2
文档链接(感谢,@gniourf_gniourf):
Function Definition Command in the POSIX spec
- 请注意,这意味着该功能符合 POSIX 标准,您也可以在
sh
(仅限 POSIX 功能)脚本中使用它。
- 请注意,这意味着该功能符合 POSIX 标准,您也可以在
关于bash - 在 bash 中从内部函数设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192785/