这个bash脚本为什么即使有拼写错误也能工作?

huangapple go评论60阅读模式
英文:

Why does this bash script work even with the typo

问题

在 if 语句中计算 a2 的表达式中,出现了大写的 'I' 而不是 'i'。我理解shell脚本是大小写敏感的,但我注意到这段代码仍然有效。有人能解释为什么吗?

英文:

So I have this bash script to find the Fibonacci sequence for n terms. Its definitely not great code, but I notices that it still works with a typo

read -p "Enter which term of fibo seq to find: " n

table=(1 1)

for i in $(seq 0 $(($n - 1)) )
do
    if [[ -z ${table[$i]} ]]; then
        a1=$(( $i - 1 ))
        a2=$(( $I - 2 ))
        val=$(( ${table[$a1]} + ${table[$a2]} ))

        table+=($val)
    fi
done

echo ${table[@]}

inside the if statement evaluating the expression for a2, there is a capital 'I' instead of 'i'. My understanding is that shellscript is case sensitive but I'm new to it. So can anyone explain why this works?

答案1

得分: 2

a2将始终为-2。从bash 4.2开始,您可以使用负索引访问数组,就像在Python中一样。因此,无论是否存在拼写错误,您始终在访问数组中的倒数第二个元素。

英文:

a2 will always be -2. Starting with bash 4.2, you can index into an array using negative indices, much like in Python. So with or without the typo, you are always accessing the second last element in the array.

答案2

得分: 1

The statement a2=$(( $I - 2 )) where $I is not declared is equal to a2=$(( - 2 )) which means a2 will always be equal to -2.

英文:

The statement a2=$(( $I - 2 )) where $I is not declared is equal to a2=$(( - 2 )) which means a2 will always be equal to -2.

huangapple
  • 本文由 发表于 2023年2月19日 05:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定