如何在 bash for 循环中设置变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4570985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set a variable inside a bash for loop?
提问by Isaac Moore
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:
我需要在 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
}
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.
请帮忙,谢谢。
回答by DVK
Use
用
for lvl in 1 2 3 4
do
key="UNLOCKED_${box}_$lvl"
done
You were missing "do"/"done" keywords wrapping around the loop body
$box_$lvlis 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 bashso that should not cause youproblems.
您缺少环绕循环体的“do”/“done”关键字
$box_$lvlbash 将其视为名称box_后跟名称为 的变量的变量lvl。这是因为_是变量名中的有效字符。要将变量名称与以下内容分开_,请使用${varname}如上所示的语法{0..24}在 bash v2(我们的服务器在这里有)中不起作用,尽管它在现代 bash 上用作范围快捷方式,因此不会导致您出现问题。

