Alex028502
Alex028502

Reputation: 3824

when using -e in bash, exclamation mark before a passing command still doesn't cause the script to fail

I thought the following script would just print 'hello' and then exit with a '1'

#!/bin/bash -e

! echo hello
echo world

However, it prints

hello
world

and exits with a 0

the following script exits with a 1:

#!/bin/bash -e

! echo hello

and so does the following

#!/bin/bash -e

echo hello | grep world
! echo hello
echo world

but for some reason the -e option doesn't manage to fail the script when a command returns a failing exit code due to a ! half way through. Can anybody offer an explanation that will make me feel better about this?

Upvotes: 4

Views: 231

Answers (1)

Eos
Eos

Reputation: 132

http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin

The -e command will fail the script for any command returning a non-zero code, except for some cases, like while loops, or commands returning 0 but inverted with the ! option. Thus your ! echo hello will return 1 (0 inverted by the !) but the -e option won't fail.

But if you make a exit status 42, you will have your script failed.

Upvotes: 3

Related Questions