User Tools

Site Tools


bash:output:get_the_output_of_a_command

This is an old revision of the document!


BASH - Output - Get the output of a command

This depends on whether you want to store the command's output (either stdout, or stdout + stderr) or its exit status (0 to 255, with 0 typically meaning “success”).


Capture the output of a command

To capture the output, you use command substitution:

output=$(command)      # stdout only; stderr remains uncaptured
output=$(command 2>&1) # both stdout and stderr will be captured

To save both output of a command; and the exit status

If you want both:

output=$(command)
status=$?

The assignment to output has no effect on command's exit status, which is still in $?.


Capture stdout and take action on exit status

If you want to capture stdout as well as taking action on success/failure, without explicitly storing or checking $?:

if output=$(command); then
    printf "it succeeded\n"
    ...

Capture stdout and stderr

What you cannot do is capture stdout in one variable, and stderr in another, using only FD redirections.

You must use a temporary file (or a named pipe) to achieve that one.

Well, you can use a horrible hack like:

cmd() { curl -s -v http://www.google.fr; }
 
result=$(
    { stdout=$(cmd) ; } 2>&1
    printf "this line is the separator\n"
    printf "%s\n" "$stdout"
)
var_out=${result#*this line is the separator$'\n'}
var_err=${result%$'\n'this line is the separator*}

Obviously, this is not robust, because either the standard output or the standard error of the command could contain whatever separator string you employ.

And if you want the exit code of your cmd (here a modification in the case of if the cmd stdout nothing)

cmd() { curl -s -v http://www.google.fr; }
 
result=$(
    { stdout=$(cmd); returncode=$?; } 2>&1
    printf "this is the separator"
    printf "%s\n" "$stdout"
    exit "$returncode"
)
returncode=$?
 
var_out=${result#*this is the separator}
var_err=${result%this is the separator*}
bash/output/get_the_output_of_a_command.1611673429.txt.gz · Last modified: 2021/01/26 15:03 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki