8

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?

jinge
  • 785
  • 1
  • 7
  • 20

2 Answers2

8

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))
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
3

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.

Viktor Khilin
  • 1,760
  • 9
  • 21