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 ]]
    echo "Your command failed to execute with exit code ${?}"
    exit 1
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?

1 Answer 1


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

if [[ $err -ne 0 ]]; then
    printf 'id failed with code %d\n' "$err" >&2
    exit 1
  • 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, 2020 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. May 7, 2020 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, 2020 at 18:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .