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"
    ...
bash/output/get_the_output_of_a_command.1611673330.txt.gz · Last modified: 2021/01/26 15:02 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki