使用变量的 Stdout 和 Stderr 重定向

Stdout & Stderr redirection using variables

我正在尝试在我的脚本中创建 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

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

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

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

并像这样使用它们:

displayoutput cmd args
displayonlyerror cmd args