piyush nath
piyush nath

Reputation: 89

Bash loop to fetch different variables

Is it possible to do something like this

#!/bin/bash 
noOfParameters=2
paramname1="test1"
paramname2="test2"
i=0
while [ $i -ne ${noOfParameters} ]
  do 
     i=`expr $i + 1`
     echo ${paramname$i}
 done

I am trying to achieve output as

test1
test2

I am getting "main.sh: line 10: ${paramname$i}: bad substitution" error

Upvotes: 0

Views: 116

Answers (2)

Walter A
Walter A

Reputation: 20002

You can use indirect references like

for ((i=1;i<3;i++)); do
   varname=paramname$i
   echo "${!varname}"
done

Perhaps you can bypass your problems with something like

set | grep -E "paramname[12]=" | cut -d"=" -f2

Upvotes: 0

Lewis Farnworth
Lewis Farnworth

Reputation: 297

I'd personally do this using an array

arr[0]="test"
arr[1]="test2"

for item in "${arr[@]}"
do
  printf "%s\n" "$item"
done

Upvotes: 1

Related Questions