简体   繁体   中英

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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