2

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 ?

svlasov
  • 9,923
  • 2
  • 38
  • 39
PBrockmann
  • 303
  • 5
  • 16
  • https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html – anishsane Mar 31 '15 at 11:17
  • 1
    @Joe: While the cause may be the same, the problem in this question is expressed much simpler than in that other question (assignment vs. increment side effect). – Michael Jaros Mar 31 '15 at 11:27

2 Answers2

5

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.

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
1

You can use the following trick:

let indice=year-1 || true
hek2mgl
  • 152,036
  • 28
  • 249
  • 266