I wonder if the code below has wrong syntax ?
#!/bin/bash
set -e
let "time_used = 1 - 1"
echo $time_used
When I run it, nothing print. The script died on let "time_used = 1 - 1"
.
If I remove set -e
in second line, I get the correct result 0
.
Why it happened?
let is a bash built-in for shell arithmentic
let "time_used = 1 - 1"
is equivalent to
(( time_used = 1 - 1 ))
however 0 in shell arithmetic means false and gives error exit status to avoid to exit with -e
|| true
can be added after command
(( 0 )) || true
let "time_used = 1 - 1" || true
|| true
allows to "bypass" -e
option for commands returning an error exit status however we can't distinguish a command that failed from a command that returns a false exit status. Other option can be to use arithmetic to return always a truthy value.
(( (time_used = 1 - 1) || 1))
Because let
returns 1
if it's result is equal 0
.
In other case, it returns 0
.
$ help let | tail -n2 Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With