Linux Shell Scripting Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

Reading the return value (status) of a command

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

cmd;
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:

#!/bin/bash 
#Filename: success_test.sh 
# Evaluate the arguments on the command line - ie success_test.sh 'ls | grep txt' 
eval $@ 
if [ $? -eq 0 ]; 
then 
    echo "$CMD executed successfully" 
else 
    echo "$CMD terminated unsuccessfully" 
fi