问题
I am struggling to understand why the bash -e
option exits this script.
It happens only when the expression calculated gives 0
:
#!/bin/bash
set -ex
table_year=( 1979 1982 1980 1993 1995 )
year=$1
let indice=year-1
real_year=${table_year[$indice]}
echo OK $real_year
Is is ok when:
./bash_test_array 2
but not when:
./bash_test_array 1
indice
is this case equals to 0
. Why the -e
option causes an exit ?
回答1:
See help let
:
Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise..
The behavior of the let
builtin is the same as for the commonly used expr
command:
Exit status is [...] 1 if EXPRESSION is null or 0 [...]
You can use arithmetic expansion instead:
indice=$(( year - 1 ))
This statement will return 0 even if the assigned expression evaluates to 0.
回答2:
You can use the following trick:
let indice=year-1 || true
来源:https://stackoverflow.com/questions/29367309/why-does-bash-with-e-option-exit-when-let-expression-evaluates-to-0