Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignore exit code in bash

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading