I am testing different things in bash scripting and I came into a problem that I cannot get an explanation for it.
I am purposely writing a wrong command, to get an exit code different from 0, but somehow it seems that I still get 0.
The code I'm executing is :
USER_NAME=$(id -uns)
if [[ ${?} -ne 0 ]]
then
echo "Your command failed to execute with exit code ${?}"
exit 1
fi
echo "Your username is ${USER_NAME}"
The output of my code is :
id: unknown option -- s
Try 'id --help' for more information.
Your command failed to execute with exit code 0
Your username is
I'm guessing that in some way, it's displaying the exit code for the echo command? Even so, if the exit code is 0, why does it enter in the if statement?
If that's the thing, then how can I make it to display the actual exit code that should be displayed?