我有一个bash脚本,它使用以下结构几乎可以完成我想要的工作:
for x in 1 2 3
do
{
[[ $x -ne 2 ]] || continue
echo $x
} &>> foo.log
done
我需要更改它,以便输出同时到达终端和日志文件。但是,这不起作用:
for x in 1 2 3
do
{
[[ $x -ne 2 ]] || continue
echo $x
} 2>&1 | tee -a foo.log
done
看起来,通过创建进程,管道阻止了我使用continue
。
当然,我可以不用continue
来重写脚本的逻辑,但是在我跳进去之前,我想知道我是否缺少一种实现我想要的更简单的方法。
您可以将输出重定向到流程替换。
for x in 1 2 3
do
{
[[ $x -ne 2 ]] || continue
echo $x
} 2>&1 > >(tee -a foo.log)
done |
# I suggest to do pipe the output to ex. `cat`, so that the output
# of process substitution will be synchronized with rest of the script
cat
但是为什么不仅仅重定向整个循环的输出呢?
for x in 1 2 3; do
[[ $x -ne 2 ]] || continue
echo $x
done 2>&1 | tee -a foo.log
您可以退出子流程。如果您愿意这样做,我建议您将{
}
替换为(
)
,只是为了安全起见,如果您有一天决定删除tee
。
for x in 1 2 3
do
{
[[ $x -ne 2 ]] || exit
echo $x
} 2>&1 | tee -a foo.log
done