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

Set redirection from inside function in 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'

但这有点难看。我宁愿将所有重定向指令都放在函数本身中。会更容易管理。我觉得这可能不可能,但想确定一下。

您可以使用 exec 内置函数(注意 exec 的效果不会在函数 returns 后被取消):

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's

您还可以使用:

#!/bin/bash

    one() {
      (
      # function commands
      ) 2> /tmp/file_one
    }

    two() {
      (
      # function commands
      ) 2> /tmp/file_two
    }

    one
    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):