2

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.

1
  • 7
    The trick most people use is to assign $? to a variable called status and then work with that.
    – rghome
    Commented Jan 25, 2023 at 16:20

1 Answer 1

4

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.