1

I'm getting started with bash programming, and am stumbling through the syntax a little. 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

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

0

2 Answers 2

2

Spaces are not optional. You need to use:

if [[ "${initialGrid[i]}" == "_" ]]; then echo "I'm here"; fi
Sign up to request clarification or add additional context in comments.

Comments

0

Spaces in bash almost always are special characters. 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]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.