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
When you are not sure how many field variables you have, you can use something like:
set
lists all the variables;grep
selects the ones starting with 'field';cut
removes the value of the variable, leaving just the name.You're looking for
${!var1}
— a Bash-specific shell parameter expansion.Output:
I got that with both
bash
andsh
running the script. Clearly, if you don't include$var1=
in theecho
, you get just the single letters you ask for.You should also consider whether your fields should be stored in a Bash array.
Why don't you use arrays? maybe something like this: