[英]BAD SUBSTITUTION: String comparison using array elements in bash
I'm getting started with bash programming, and am stumbling through the syntax a little. 我开始使用bash编程,并且在语法上有些绊脚石。 The following is part of the code to play tic-tac-toe from the command line.
以下是从命令行播放井字游戏的部分代码。
i=0
initialGrid=('_' '_' '_' '_' '_' '_' '_' '_' '_')
if [ "${ initialGrid[ $i ] }" = "_" ]; then
echo "I'm here"
fi
However I get the following error 但是我收到以下错误
tic.sh: line 48: ${ initialGrid[ $i ] }: bad substituion
So the echo never gets executed 所以回声永远不会执行
I was able to substitute the above if statement and do the following without error 我能够替换上面的if语句,并执行以下操作而不会出错
element=" $initialGrid[$i] "
if [ "${!element}" = "_" ]; then
echo "Element equals underscore"
fi
But again, the echo never gets execute even though i believe it clearly should 但是再说一次,即使我相信它显然应该执行,回声也永远不会执行
Spaces are not optional. 空格不是可选的。 You need to use:
您需要使用:
if [[ "${initialGrid[i]}" == "_" ]]; then echo "I'm here"; fi
Spaces in bash almost always are special characters. bash中的空格几乎总是特殊字符。 In your first case:
在第一种情况下:
i=0
initialGrid=('_' '_' '_' '_' '_' '_' '_' '_' '_')
if [ "${ initialGrid[ $i ] }" = "_" ]; then
echo "I'm here"
fi
You need to replace the line with the condition with 您需要将条件替换为
if [ "${initialGrid[$i]}" = "_" ]; then
In your second case, you are padding the value with spaces, but then trying to compare it to the value without spaces, _
is not the same as _
. 在第二种情况下,您用空格填充值,但随后尝试将其与不带空格的值进行比较,
_
与_
。 You are also not dereferencing the array correctly. 您也没有正确取消对数组的引用。
element=" $initialGrid[$i] "
if [ "${!element}" = "_" ]; then
echo "Element equals underscore"
fi
Replace the first line with element="${initialGrid[$i]}"
将第一行替换为
element="${initialGrid[$i]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.