I'm testing about exit codes in bash and I coded the following script:
read -p "Path: " path
dr $path 2> /dev/null
echo "Command output level: "$?
if [ $? = 0 ]
then
echo "Command success"
elif [ $? = 127 ]
then
echo "Command not found"
else
echo "Command failed or not found"
fi
Now, I've been doing some research and I want to know if there's a way to make the very last "echo" avoid changing the exit code, if there's any I haven't found it.
I understand that the exit code is changed from 127 (yes, dr is on purpose to provoke the exit code) to 0 when I executed it.
CodePudding user response:
Every command sets $?
. If you wish to preserve the exit status of a specific command, you must save the value immediately.
dr $path 2> /dev/null
dr_status=$?
echo "Command output level: $dr_status"
if [ $dr_status = 0 ]
then
echo "Command success"
elif [ $dr_status = 127 ]
then
echo "Command not found"
else
echo "Command failed or not found"
fi
However, you can sometimes avoid repeated commands that would reset $?
. For example,
dr $path 2> /dev/null
case $? in
0) echo "Command success" ;;
127) echo "Command not found" ;;
*) echo "Command failed or not found" ;;
esac