1

In a shell script, I have a list of variables that I've ordered as $a, $b, $c, etc. I'd like to print these variables without having to list all the variables. My current code is as follows:

a=1
b=2
c=3
d=4
e=5
f=6
g=7

for x in $a$b$c$d$e$f$g
do
  echo "$x"
done

Can I shorten $a$b$c$d$e$f$g to something that refers to $a through $g?

2
  • 1
    Do you realize echo will run just once? Why for then? Is it because some characters in variables (c=" " or d=" /* ") can make it run more than once? This only makes the code more awkward. Is this really what you want to do? Jun 24, 2019 at 19:57
  • Not necessarily. I'm just trying to understand how to shorten the line $a$b$c$d$e$f$g and wanted to provide an example. I wouldn't necessarily need the for loop.
    – Chlotron
    Jun 24, 2019 at 20:21

1 Answer 1

1

Using "evil" eval:

eval echo \"$(printf '$%s' {a..g})\"

Note that I used escaped quotes which is needed for correct output if your variables should contain space characters.


Or use the corrected for-loop of the first answer:

for x in {a..g}; do printf "${!x}"; done


Or use an array in your script. It's a different syntax, but is easier to handle if you need all values at once. Here's a small example:

array=(1 2 3 4 x 6)
array+=(7)  # add one more
array[4]=5  # modify element at index 4
printf '%s' "${array[@]}"

Note that the last two printf statements don't end with a newline.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .