Why does Bash with -e option exit when 'let' expression evaluates to 0? [duplicate]

廉价感情. 提交于 2021-02-05 06:49:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!