【问题标题】:Stdout & Stderr redirection using variables使用变量的标准输出和标准错误重定向
【发布时间】:2019-11-19 17:25:48
【问题描述】:

我正在尝试在我的脚本中创建 2 个变量以将错误和输出重定向到文件并仅显示屏幕中的错误和其他变量以仅在屏幕中显示输出。当我把它作为一个变量它不起作用。变量为空。有什么帮助吗?

#!/bin/bash
timestamp="`date +%Y%m%d%H%M%S`"
displayonlyerror="2>&1 >> /tmp/postinstall_output_$timestamp.log | tee -a /tmp/postinstall_output_$timestamp.log"
displayoutput="2>&1 |tee -a /tmp/postinstall_output_$timestamp.log"

echo "No screen session found" $displayoutput
ech "No screen session found" $displayerror

【问题讨论】:

  • 那么最好的处理方法是什么?
  • 非常感谢。它奏效了。

标签: bash shell variables stdout stderr


【解决方案1】:

它不会那样工作,shell 在对其他令牌执行扩展之前解析重定向。相反,将displayonlyerrordisplayoutput 定义为类似函数(file 是日志文件名,您可以更改它):

displayonlyerror() {
    "$@" 2>&1 >>file | tee -a file
}

displayoutput() {
    "$@" 2>&1 | tee -a file
}

并像这样使用它们:

displayoutput cmd args
displayonlyerror cmd args

【讨论】:

  • 我已经有一个名为 color 的函数,用于在执行命令时突出显示错误。像下面这样的东西用于之前执行。 color()(set -o pipefail;"$@" 2>&1>&3|sed $'s,.*,\e[31m&\e[m,'>&2)3>&1 color command1 2>&1 |tee -a /tmp/postinstall_output_$timestamp.log 因为我们创建了另外 2 个函数来存储 stderr 和 stdout 我们现在如何调用?有没有办法在一个班轮中一次调用 2 个函数?
  • 你试过displayoutput color cmd args或类似的吗?
  • 成功了。我正在尝试相反的方式,如 color displayoutput cmd...非常感谢:-)
猜你喜欢
  • 2012-03-30
  • 1970-01-01
  • 2011-10-11
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
相关资源
最近更新 更多