Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 287
Alex028502 Avatar asked Oct 29 '25 04:10

Alex028502


1 Answers

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.

like image 127
Eos Avatar answered Oct 31 '25 21:10

Eos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!