2

I need to set a variable inside of a bash for loop, which for some reason, is not working for me. Here is an excerpt of my script:

function unlockBoxAll
{
appdir=$(grep -i "CutTheRope.app" /tmp/App_list.tmp)
for lvl in {0..24}
key="UNLOCKED_$box_$lvl"
plutil -key "$key" -value "1" "$appdir/../Library/Preferences/com.chillingo.cuttherope.plist" 2>&1> /dev/null
successCheck=$(plutil -key "$key" "$appdir/../Library/Preferences/com.chillingo.cuttherope.plist")
if [ "$successCheck" -eq "1" ]; then
 echo "Success! "
    else
 echo "Failed: Key is $successCheck "
fi
done
}

As you can see, I try to write to a variable inside the loop with:

key="UNLOCKED_$box_$lvl"

But when I do that, I get this:

/usr/bin/cutTheRope.sh: line 23: syntax error near unexpected token `key="UNLOCKED_$box_$lvl"'
/usr/bin/cutTheRope.sh: line 23: `key="UNLOCKED_$box_$lvl"'

What am I not doing right? Is there another way to do this?

Please help, thanks.

Isaac Moore
  • 240
  • 1
  • 2
  • 15

1 Answers1

4

Use

for lvl in 1 2 3 4 
do
    key="UNLOCKED_${box}_$lvl"
done
  1. You were missing "do"/"done" keywords wrapping around the loop body

  2. $box_$lvl is treated by bash as a variable with the name box_ followed by variable with the name lvl. This is because _ is a valid character in a variable name. To separate the variable name from following _, use ${varname} syntax as shown above

  3. {0..24} does not work in bash v2 (which our servers have here) though it works as a range shortcut on modern bash so that should not cause youproblems.

Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327