User Tools

Site Tools


bash:output:check_exit_status

BASH - Output - Check Exit Status

To get the exit status, you use the special parameter $? after running the command:

command
status=$?

Check exit status

If you don't actually want to store the exit status, but simply want to take an action upon success or failure, just use if:

if command; then
    printf "it succeeded\n"
else
    printf "it failed\n"
fi

Exit Status from a piped command - use PIPESTATUS

What if you want the exit status of one command from a pipeline?

If you want the last command's status, no problem – it's in $? just like before.

If you want some other command's status, use the PIPESTATUS array.

NOTE: This is BASH only.

In the case of Zsh, it's lower-cased pipestatus).

Say you want the exit status of grep in the following:

grep foo somelogfile | head -5
status=${PIPESTATUS[0]}

Bash 3.0 added a pipefail option as well, which can be used if you simply want to take action upon failure of the grep:

set -o pipefail
if ! grep foo somelogfile | head -5; then
    printf "uh oh\n"
fi

bash/output/check_exit_status.txt · Last modified: 2021/01/26 14:58 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki