如何在 bash for 循环中设置变量?
我需要在 bash for 循环内设置一个变量,由于某种原因,这对我不起作用。这是我的脚本的摘录:
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
}
如您所见,我尝试在循环内写入变量:
key="UNLOCKED_$box_$lvl"
但是当我这样做时,我得到这样的信息:
/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"'
我做错了什么?还有其他方法可以做到这一点吗?
请帮忙,谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
您缺少环绕循环体的“do”/“done”关键字
$box_$lvl bash 将
视为名称为box_
的变量,后跟名称为lvl
的变量。这是因为_
是变量名称中的有效字符。要将变量名称与后面的_
分开,请使用如上所示的${varname}
语法{0..24}
不会尽管它在现代 bash 上用作范围快捷方式,因此不会引起问题。Use
You were missing "do"/"done" keywords wrapping around the loop body
$box_$lvl
is treated by bash as a variable with the namebox_
followed by variable with the namelvl
. This is because_
is a valid character in a variable name. To separate the variable name from following_
, use${varname}
syntax as shown above{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.