当一个整数变量被滥用(通过尝试将一个字符串存储到该变量中)时,Bash shell 有没有办法抛出运行时错误?

tal*_*150 0 bash debugging shell-script

Linux Mint 上的 Bash 4.3 shell:

我意识到 Bash shell 是无类型的,或者具有非常弱的打字形式。但是,是否可以调用 Bash shell(例如使用某些选项),以便当声明的整数变量被滥用(例如,通过尝试将字符串存储到该整数变量中)时,shell 将抛出运行时错误?

示例代码:

declare -i age

age=23
echo "$age"   # result is 23
age="hello"
echo "$age"   # result is not the string hello - wish I could get an error message here!```


Run Code Online (Sandbox Code Playgroud)

gle*_*man 5

抛出错误的方法是:

set -u
# or
set -o nounset
Run Code Online (Sandbox Code Playgroud)

然后:

$ set -u
$ declare -i age
$ age=hello
bash: hello: unbound variable
Run Code Online (Sandbox Code Playgroud)

但是,如果它不是未绑定的变量,则它不会总是以您期望的方式“工作” :

$ hello=world
$ age=hello
bash: world: unbound variable

$ hello=42
$ age=hello
$ echo $age
42

$ hello=""
$ age=hello
$ echo $age
0
Run Code Online (Sandbox Code Playgroud)

我开始认为declare -i. 它可以让你在没有算术语法的情况下进行算术运算,我认为这只会增加一层混乱。