Search code examples
shellunixhttp-redirectexit-code

Shell exit codes inconsistants with simple command


I have an issue that should not be too hard to solve, I just can't figure what I'm doing wrong.

I need to test if a command is successful or not, and the command needs to be executed from a script. The command is:

curl 127.0.0.1:5000 &> /dev/null

Right now there is no server running, so it should always fail. And it does fail when I execute it from a command line. However when I run it from inside a shell script, it fails but the exit code is 0. What could the cause of that be?

Here is the script:

if curl 127.0.0.1:5000 &> /dev/null
then
    echo "sucess"
    exit 0
else
    echo "failure"
    exit 1
fi

And here is the output:

success
curl: (7) Failed to connect to 127.0.0.1 port 5000: Connection refused

However, it does work as expected if I remove the redirection (I'm quite a beginner in shell code, but the redirection shouldn't also redirect the exit code right? So I really don't know what this means)

here is the code without redirections that works as expected (therefore that indicates a failure and has an exit code of 1):

if curl 127.0.0.1:5000
then
    echo "sucess"
    exit 0
else
    echo "failure"
    exit 1
fi

Anyone has an idea?

Edit: I was launching the script with sh script_name.sh in zsh. When I use zsh script_name.sh it now works normally. I still don't fully understand why but at least it works!


Solution

  • "&> /dev/null" is interpreted differently in Bourne shell (sh), The "&" puts the command in background, you can test it with "sleep 100 &>/dev/null". Since it successfully put the command in background, it is a success, and the exit status of the backgrounded command is disregarded.

    If you want it to work in Bourne shell (sh), use the traditional syntax ">/dev/null 2>&1", and it will work in newer shells as well, i.e. it is more compatible.

    In a system where sh is linked to bash, it will work as is.