简体   繁体   English

重定向bas​​h输出

[英]Redirecting bash output

I'm having a little trouble with a script I am running. 我正在运行的脚本有点麻烦。 I cannot get output redirected when the script is successful. 脚本成功后,我无法重定向输出。 I need to just pass it to /dev/null as I really don't care about it. 我只需要将它传递给/ dev / null即可,因为我真的不在乎它。

if ! p4 -p 1667 -c prefetch -Zproxyload sync //bob/...; then
    printf "\nFailed to Sync //bob \n\n" &> $OUTPUT_LOG
else &>/dev/null
fi

What am I doing wrong? 我究竟做错了什么?

You have to decide what you want to do with the output before you generate it — before you run the command. 您必须先确定要对输出执行什么操作,然后再生成命令-运行命令。 If you want the output preserved to go in the log file when there's a problem, but to discard it when there is no problem, you will need to save the output, decide whether there was a problem, and then deal with it. 如果要在出现问题时将保留的输出保存到日志文件中,而在没有问题时将其丢弃,则需要保存输出,确定是否有问题,然后进行处理。

Saving the output (standard output and standard error) means either putting it in a file or in a variable. 保存输出(标准输出和标准错误)意味着将其放入文件或变量中。 Here, a variable is probably appropriate. 在这里,一个变量可能是合适的。

output=$(p4 -p 1667 -c prefetch -Zproxyload sync //bob/...  2>&1)
if [ $? != 0 ]
then
    {
    echo "$output"
    printf "\nFailed to Sync //bob\n\n"
    } > $OUTPUT_LOG
fi

The alternative, using files, might be better if the output can be extremely copious, but it is more complex to make sure that the files are properly named (see mktemp ) and much more complex to make sure that the files are properly removed even if the script is interrupted (see trap ). 如果输出可能非常丰富,则使用文件的替代方法可能会更好,但要确保正确命名文件(请参阅mktemp )要复杂得多,而要确保正确删除文件也要复杂得多,即使脚本被中断(请参阅trap )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM