0

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?

7

In your code, within the if statement, the exit status that gets printed is the exit status of the test [[ ${?} -ne 0 ]]. The value $? is always the exit status of the most recently executed command, and the test counts as a command, at least with regards to setting the value of $? to its result.

If you want to print the exit status of id, assign it to a variable whose value won't change,

id -uns
err=$?

if [[ $err -ne 0 ]]; then
    printf 'id failed with code %d\n' "$err" >&2
    exit 1
fi
  • This non-POSIX script does not execute test... [[ is part of the ksh syntax and run as part of the interpreter, but not as a builtin command. It however seems that this part of the interpreter resets the remembered exit code. – schily May 6 '20 at 19:08
  • Why though does the script execute both echos? I would have expected it to exit after the first, and not make it to the second. – pericynthion May 7 '20 at 17:56
  • @pericynthion They are not showing the code that they actually ran. The output that they show comes from a version of their code without the exit 1 statement in it. It was probably added later. – Kusalananda May 7 '20 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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