在bash中设置内部函数重定向



我想做一些这样的事情:

one() {
  redirect_stderr_to '/tmp/file_one'
  # function commands
}
two() {
  redirect_stderr_to '/tmp/file_two'
  # function commands
}
one
two

这将连续运行onetwo,将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):

  • Shell Functions Bash参考手册

  • POSIX规范中的功能定义命令

      请注意,这意味着该功能是posix兼容的,您也可以在sh(仅posix -features)脚本中使用它。

您可以使用内置的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

现在,如果您只想将重定向应用于函数,最好的方法是在mklement0的答案中。

您也可以使用:

#!/bin/bash
    one() {
      (
      # function commands
      ) 2> /tmp/file_one
    }
    two() {
      (
      # function commands
      ) 2> /tmp/file_two
    }
    one
    two

最新更新