简体   繁体   中英

redirect command to a variable or a file based on its exit code bash script?

I want to redirect stderr or stdout of a command to a file or a variable, based on exit code of the command. Ie, if exit code is zero, then I would redirect stdout to file, otherwise I would redirect to stderr.

Unfortunately, there's no way to capture both stdout and stderr and store them in different variables without executing the command twice. Instead, you will have to redirect the output to different temporary files and then keep the one you want based on the exit code. For example:

#Send the output to different files
dosomething >tempout 2>temperr

case $? in
    0)
        mv tempout outfile.txt
        rm temperr;;
    1)
        mv temperr outfile.txt
        rm tempout;;
    2)
        mv tempout outfile.txt
        cat temperr >> outfile.txt
        rm temperr;;
    3)
        var=$(cat tempout)
        rm tempout temperr
    #...etc
esac

should do the job. Don't forget to complete the case statement if you want to send stderr (or both) to a variable.

Try something like this:

a) catch the output:

OUT=`grep -c test myfile.txt`

b) redirect (without doing anything else in the meantime) the environment variable OUT according to the exit status located in the special variable $? :

if [ "$?" -eq 0 ];
then
    echo "succes with output=$OUT";
else
    echo "failure with output=$OUT";
fi

Of course you have to put the second part exactly after the first one in order to keep the right value in $? .

If the output is too large; redirect it first to a temporary file, then rename the temporary file according to the exit code.

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