如何在 bash for 循环中设置变量?

发布于 2024-10-09 13:38:14 字数 866 浏览 0 评论 0原文

我需要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望喜 2024-10-16 13:38:14

使用

for lvl in 1 2 3 4 
do
    key="UNLOCKED_${box}_$lvl"
done
  1. 您缺少环绕循环体的“do”/“done”关键字

  2. $box_$lvl bash 将 视为名称为 box_ 的变量,后跟名称为 lvl 的变量。这是因为 _ 是变量名称中的有效字符。要将变量名称与后面的 _ 分开,请使用如上所示的 ${varname} 语法

  3. {0..24} 不会尽管它在现代 bash 上用作范围快捷方式,因此不会引起问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文