英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论