Reading the return value (status) of a command

The return value of a command is stored in the $? variable.

echo $?;

The return value is called exit status. This value can be used to determine whether a command completed successfully or unsuccessfully. If the command exits successfully, the exit status will be zero, otherwise it will be a nonzero value.

The following script reports the success/failure status of a command:

# Evaluate the arguments on the command line - ie 'ls | grep txt' 
eval $@ 
if [ $? -eq 0 ]; 
    echo "$CMD executed successfully" 
    echo "$CMD terminated unsuccessfully" 

Get Linux Shell Scripting Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.