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

标签 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'

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

最佳答案

最简单和最可靠的方法是使用函数级重定向:注意重定向命令是如何应用于整个函数,在下面的结束 } 之后,作用于每个函数(无需重置):

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

关于bash - 在 bash 中从内部函数设置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192785/

相关文章:

algorithm - 如果 SNMP 计数器的值小于以前的读数,绘图工具应该如何表现?

python - 将嵌入式 Python IO 重定向到使用 AllocConsole 创建的控制台

bash 从命令行参数设置变量

linux - 嵌套的 bash 命令引用问题

linux - Bash 相对日期(x 天前)

c - 保存一个程序的输入

C++ - 使用 io 重定向输入和输出多个整数

installation - 从 Inno Setup 执行带有输出重定向的程序

powershell - 为什么 PowerShell 重定向 >> 更改文本内容的格式?

python - 尝试运行 Python35 脚本时使用 nohup 吗?