skip to Main Content

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

2

Answers


  1. 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/}")
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search