echo the set of variables while going through a loop

六月ゝ 毕业季﹏ 提交于 2020-01-15 11:59:24

问题


Can someone help me. I've been trying alternatives but I still get the same output.

Here is my script

  #!/bin/sh

  field1="a"
  field2="s"
  field3="d"
  field4="f"
  field5="g"

  for i in {1..5}
  do

    var1="field"$i
    echo $var1

    var2="$"$var1
    echo $var2 

    echo $field1

  done

Here is my output

  field1
  $field1
  a
  field2
  $field2
  a
  field3
  $field3
  a
  field4
  $field4
  a
  field5
  $field5
  a

what I'm trying to do is get an output like

a
s
d
f
g

回答1:


You're looking for ${!var1} — a Bash-specific shell parameter expansion.

field1="a"
field2="s"
field3="d"
field4="f"
field5="g"

for i in {1..5}
do
    var1="field"$i
    echo $var1=${!var1}
done

Output:

field1=a
field2=s
field3=d
field4=f
field5=g

I got that with both bash and sh running the script. Clearly, if you don't include $var1= in the echo, you get just the single letters you ask for.

You should also consider whether your fields should be stored in a Bash array.




回答2:


Why don't you use arrays? maybe something like this:

#!/bin/sh

  field[1]="a"
  field[2]="s"
  field[3]="d"
  field[4]="f"
  field[5]="g"

  for i in {1..5}
  do

    echo ${field[i]}

  done



回答3:


When you are not sure how many field variables you have, you can use something like:

set | grep "^field" | cut -d= -f2

set lists all the variables; grep selects the ones starting with 'field'; cut removes the value of the variable, leaving just the name.



来源:https://stackoverflow.com/questions/28102828/echo-the-set-of-variables-while-going-through-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!