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

时间:2015-10-17 23:45:23

标签: bash io-redirection

我想做这种形式的事情:

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'

但这有点难看。我宁愿在函数本身内部拥有所有重定向指令。它更容易管理。我有一种感觉,这可能是不可能的,但我想确定。

3 个答案:

答案 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):

答案 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

现在,如果您只想将重定向应用于该功能,最好的方法是在mklement0' answer

答案 2 :(得分:2)

您也可以使用:

#!/bin/bash

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

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

    one
    two