Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A strange error of 'let' in bash [duplicate]

Tags:

bash

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?

like image 634
jinge Avatar asked Dec 27 '17 09:12

jinge


2 Answers

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))
like image 125
Nahuel Fouilleul Avatar answered Oct 06 '22 01:10

Nahuel Fouilleul


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.

like image 41
Viktor Khilin Avatar answered Oct 05 '22 23:10

Viktor Khilin