我想做这种形式的事情:
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'
但这有点难看。我宁愿在函数本身内部拥有所有重定向指令。它更容易管理。我有一种感觉,这可能是不可能的,但我想确定。
答案 0 :(得分:4)
最简单,最强大的方法是使用 功能级重定向:注意重定向命令如何应用于整个功能,在下面的}
结束后作用于每个功能(无需重置):
# 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
sh
(仅限POSIX功能)脚本中使用它。答案 1 :(得分:3)
您可以使用exec
内置(注意函数返回后exec
的效果不会被取消):
one() {
exec 2> '/tmp/file_one'
# function commands
}
two() {
exec 2> '/tmp/file_two'
# function commands
}
one # stderr redirected to /tmp/file_one
echo "hello world" >&2 # this is also redirected to /tmp/file_one
exec 2> "$(tty)" # here you are setting the default again (your terminal)
echo "hello world" >&2 # this is wrtitten in your terminal
two # stderr redirected to /tmp/file_two
答案 2 :(得分:2)
您也可以使用:
#!/bin/bash
one() {
(
# function commands
) 2> /tmp/file_one
}
two() {
(
# function commands
) 2> /tmp/file_two
}
one
two