0

To make things clear, I would short my bash script:

#!/bin/bash -e  

p_time=$(expr 0 - 0)
echo ?
echo "process time(sec) is: " ${p_time}  

The file would end before "echo ?", but if I change "p_time=$(expr 0 - 0)" to "p_time=$(expr 3 - 0)", the file would end correctly.
However, if I removed "-e" in the first sentence, the file ended correctly too.
Why would this happen?

styshoo
  • 563
  • 4
  • 9
  • 1
    This is one reason why many people recommend not using the `-e` option; a non-zero exit code doesn't always indicate an *error*. – chepner Oct 21 '17 at 13:56
  • If you have any questions about just how sane and predictable the behavior of `set -e` is, consider going through the exercises in [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105), or reviewing the table demonstrating incompatibilities between different shells' implementations at https://www.in-ulm.de/~mascheck/various/set-e/ – Charles Duffy Feb 05 '18 at 01:13
  • 1
    BTW, as an aside, `expr` is a relic of the 1970s and shouldn't be used in modern scripts. `p_time=$((0 - 0))` is guaranteed to work with every shell compliant with the 1991 POSIX.2 standard, and is *far* more efficient (as it avoids `fork()`ing off a subprocess). – Charles Duffy Feb 05 '18 at 01:15

1 Answers1

2

bash -e means Exit immediately if a command exits with a non-zero status.

The result of 0 - 0 is 0, so the exit code of expr 0 - 0 is 1 and Bash will exit immediately. If you remove -e, Bash will ignore the exit code of expr 0 - 0 and will execute all commands in your script.

haolee
  • 892
  • 9
  • 19