目前我正在使用一种逻辑来检测脚本是否在 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/