如何在循环内部访问按循环顺序命名的变量?
我试图了解是否可以在循环中创建一组基于另一个变量(使用 eval)进行编号的变量,然后在循环结束之前调用它。
作为一个例子,我编写了一个名为 Question 的脚本(第一个命令是显示变量 $tab 的内容是什么)
(23:32:12\[[email protected])
[~/bin]$ listQpsk 40|grep -w [1-4]
40 SMANHUBAQPSK1 1 1344 1195 88
40 SMANHUBAQPSK1 2 1668 1470 88
40 SMANHUBAQPSK1 3 1881 1539 81
40 SMANHUBAQPSK1 4 1686 1409 83
(23:18:42\[[email protected])
[~/bin]$ cat question
#!/usr/bin/bash
tab=`listQpsk 40|grep -w [1-4]`
seq=1
num=4
until [[ $seq -gt $num ]];do
eval count$seq=`echo "$tab"|grep -w $seq|awk '{print $5}'`
seq=$(($seq+1))
done
echo $count1
echo $count2
echo $count3
echo $count4
当我运行这个脚本时,我得到
(23:32:23\[[email protected])
[~/bin]$ ./question
1195
1471
1538
1409
的正是我所期望的,但是有没有办法移动echo 命令位于until 循环内部,以便循环的一部分回显刚刚创建的变量的值。 类似于:
until [[ $seq -gt $num ]];do
eval count$seq=`echo "$tab"|grep -w $seq|awk '{print $5}'`
seq=$(($seq+1))
echo "$count$seq"
done
PS:抱歉,如果我的格式不对...第一次在这里发帖,我只知道 Reddit 上的 Markdown。
I'm trying to understand if it's possible to create a set of variables that are numbered based on another variable (using eval) in a loop, and then call on it before the loop ends.
As an example I've written a script called question (The fist command is to show what is the contents of the variable $tab)
(23:32:12\[[email protected])
[~/bin]$ listQpsk 40|grep -w [1-4]
40 SMANHUBAQPSK1 1 1344 1195 88
40 SMANHUBAQPSK1 2 1668 1470 88
40 SMANHUBAQPSK1 3 1881 1539 81
40 SMANHUBAQPSK1 4 1686 1409 83
(23:18:42\[[email protected])
[~/bin]$ cat question
#!/usr/bin/bash
tab=`listQpsk 40|grep -w [1-4]`
seq=1
num=4
until [[ $seq -gt $num ]];do
eval count$seq=`echo "$tab"|grep -w $seq|awk '{print $5}'`
seq=$(($seq+1))
done
echo $count1
echo $count2
echo $count3
echo $count4
When I run this I get
(23:32:23\[[email protected])
[~/bin]$ ./question
1195
1471
1538
1409
Which is exactly what I would expect, but is there a way to move the echo commands inside of the until loop so that part of the loop is echoing the value of the variable that was just created. Something like:
until [[ $seq -gt $num ]];do
eval count$seq=`echo "$tab"|grep -w $seq|awk '{print $5}'`
seq=$(($seq+1))
echo "$count$seq"
done
PS: Sorry if my formatting is off...first time posting here, and I only know markdown from reddit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用间接:
不需要再次评估。
Use indirection:
No need for another eval.
不完全回答你的问题,但是......你知道 bash 有数组变量吗?
或者没有数组:
Not exactly answering your question, but... did you know bash has array variables?
Or without arrays:
是的,像这样(至少在 bash 中):
Yes, like this (in bash at least):
尝试一下:
某些版本的 shell 还允许您使用 ${!var} 间接引用变量
Try this:
some versions of shell also let you use ${!var} to indirectly reference variables