代码:
#!/bin/bash
declare -i number
# The script will treat subsequent occurrences of "number" as an integer.
number=3
echo "Number = $number" # Number = 3
number=three
echo "Number = $number" # Number = 0
# Tries to evaluate the string "three" as an integer.
当我将字符串number
分配给"three"
时,我无法弄清楚为什么number
发生了变化。我认为number
应该保持不变。这真让我感到惊讶。
答案 0 :(得分:2)
来自declare
的{{1}}部分:
man bash
来自-i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION) is performed when the variable is assigned a value.
的{{1}}部分:
ARITHMETIC EVALUATION
总之,这些明确表明您所看到的行为是预期的行为。在算术上评估字符man bash
The value of a variable is evaluated as an arithmetic expression when...a variable which has been given the integer attribute using declare -i is assigned a value. A null value evaluates to 0.
t
h
r
时,生成的e
值将被评估为e
,其中然后被赋值给变量null
。
bash中的所有赋值都首先解释为字符串。 0
首先将number
number=10
解释为字符串,将其识别为有效整数,并保持原样。 1
在语法和语义上与0
一样有效,这就是为什么在将number=three
的评估值分配给number=10
后,您的脚本会继续而没有任何错误。