bash - 是否可以使用变量来定义 bash 上的标准输出?

标签 bash

目前我正在使用一种逻辑来检测脚本是否在 cron 或 tty 中运行,因此当在 tty 中运行时,脚本输出显示在屏幕上,当脚本作为计划任务运行时,输出将显示到一个文件。

到目前为止,我发现处理此问题的唯一方法是使用 eval,但如果存在替代方案,则不鼓励使用 eval。 所以我的问题是,这段代码有其他选择吗?

#!/bin/bash
#Var to store interactive session
INTERACTIVE=0
LOG=/tmp/test.file

if [ "$INTERACTIVE" -eq 1 ]; then
    OUT=" 2>&1"
else
    OUT=" &>> $LOG"
fi

echo "Test string!" $OUT #will output "Test string! &>> /tmp/test.file"
eval echo "Test string!" $OUT #will write to the file

最佳答案

Is possible to use variable to define the stdout on bash?

不,这是不可能的。相反,重定向标准输出。

if [ "$INTERACTIVE" -eq 1 ]; then
    exec 2>&1
else
    exec 1>>"$LOG" 2>&1
fi

或者,编写一个包装函数:

if [ "$INTERACTIVE" -eq 1 ]; then
    out() { "$@" 2>&1; }
else
    out() { "$@" 1>>"$LOG" 2>&1; }
fi

out echo "test string!"

关于bash - 是否可以使用变量来定义 bash 上的标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75765877/

相关文章:

string - 在 bash 中拆分字符串的最快方法

php - 在浏览器上运行 php 脚本通过 shell 执行 hadoop 命令

python - 查找python脚本所需的模块

linux - 设置 SSH 终端的前景色

linux - 仅从 linux 终端中的文件获取括号内的文本

linux - 将多行命令输出传递给 echo 仅输出单行

python - 如何在 bash 或 python 中检查 Ubuntu 程序 coredump?

javascript - 将 BASH 的日期格式转换为 JavaScript 的日期格式

bash - wget 手动工作但在 Chef bash 中失败

bash - 在 for 循环中迭代有序路径变量