echo the set of variables while going through a lo

2019-08-08 00:50发布

问题:

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.