Yagami
Yagami

Reputation: 31

How to create list in shell using for loop

I am trying to create a new array using for loop

Images="alpine ubuntu centos"


Image_tags="$(for i in $Images; do
r_madoori1/$i
done)"


echo $Image_tags

I am expecting

Image_tags="r_madoori1/alpine r_madoori1/ubuntu r_madoori1/centos"

instead i am getting below error

./shell.sh: line 7: r_madoori1/alpine: No such file or directory
./shell.sh: line 7: r_madoori1/ubuntu: No such file or directory
./shell.sh: line 7: r_madoori1/centos: No such file or directory

Upvotes: 0

Views: 5035

Answers (2)

chepner
chepner

Reputation: 531125

The for loop repeats commands; it's doesn't build a list of values. You could write something like

# OK
Image_tags="$(for i in $Images; do
 echo -n "r_madoori1/$i "
done)"

but it would be simpler to perform multiple assignments from the, rather than embed a loop in a single assignment.

# Better
for i in $Images; do
  Image_tags="$Image_tags r_madoori1/$i"
done

If you are using bash, though, you should use real arrays, not space-separated strings.

# Best
Images=(alpine ubuntu centos)
for i in "${Images[@]}"; do
  Image_tags+=( "r_maddori1/$i" )
done

or more concisely

Images=(alpine ubuntu centos)
Image_tags=("${Images[@]/#/r_madoori1/}")

Upvotes: 2

anubhava
anubhava

Reputation: 785128

Without using any loop you can do this in bash:

Images="alpine ubuntu centos"

Image_tags="r_madoori1/${Images// / r_madoori1\/}"

echo "$Image_tags"

Output:

r_madoori1/alpine r_madoori1/ubuntu r_madoori1/centos

Upvotes: 2

Related Questions