Bourne Shell 构建并引用变量
我有一个运行的 shell,其中预设的环境变量包括:
FOOCOUNT=4
FOO_0=John
FOO_1=Barry
FOO_2=Lenny
FOO_3=Samuel
我无法更改获取此数据的方式。
我想运行一个循环来生成变量并使用内容。
echo "Hello $FOO_count"
然而,这个语法是错误的,这就是我正在寻找的......
count=$FOOCOUNT
counter=0
while [ $counter -lt $count ]
do
#I am looking for the syntax for: <<myContructedVar= $ + 'FOO_' + $counter>>
counter=`expr $counter + 1`
echo "Greeting #$counter: Hello, ${myContructedVar}."
done
非常感谢
I have a shell that runs where the preset env variables include:
FOOCOUNT=4
FOO_0=John
FOO_1=Barry
FOO_2=Lenny
FOO_3=Samuel
I can not change the way I get this data.
I want to run a loop that generates up the variable and uses the contents.
echo "Hello $FOO_count"
This syntax is however wrong and that is what I am searching for...
count=$FOOCOUNT
counter=0
while [ $counter -lt $count ]
do
#I am looking for the syntax for: <<myContructedVar= $ + 'FOO_' + $counter>>
counter=`expr $counter + 1`
echo "Greeting #$counter: Hello, ${myContructedVar}."
done
Thanks very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关键是
eval
:循环算术是老派的——我编写代码的方式。现代 shell 内置了更多算术 - 但问题被标记为 Bourne shell。
The key is
eval
:The loop arithmetic is old school - the way I write the code. Modern shells have more arithmetic built in - but the question is tagged Bourne shell.
您将需要一个
eval
和一个延迟的印记:但除非索引对您来说确实很重要,否则您可能会使用
并删除命名错误的伪数组。而且,如果您对
foo_x
和 的数量有上限,则各种 foo 中没有特殊字符(特别是$ 中没有字符IFS
(默认为
),那么您可以使用 shell 的空参数折叠功能:并允许 shell 忽略 unset foo_x
You'll need an
eval
and a deferred sigil:but unless the index is truly important to you, you might use
and get rid of the badly named pseudo-array. And, if you have an upper bound on the number of the number of
foo_x
and there are no special characters in the various foos (in particular no character in$IFS
which defaults to<space><tab><return>
) then you can use the null-argument collapsing feature of the shell and:and allow the shell to ignore unset
foo_x
我已经很长时间没有使用过 Bourne shell,但是你尝试过 eval 命令吗?
It's been a very long time since I've done any Bourne shell but have you tried the eval command?