0

I have a for loop in my bash script.

for dir in $directories
do
        dockerfile=$(find ./repo/$dir -name "Dockerfile");
        docker build -f $dockerfile . -t $dir:version;
        new_image=$(echo "$dir:version" | cut -d '/' -f2);
done

How can I pass $new_image output to another variable?

If I do something like this

new_image=$(echo "$image:version" | cut -d '/' -f2 >> list_images.txt)

I get the list of docker images in my .txt file but is there a way to pass the output to a variable? And update that variable value on each iteration?

The expected output after one iteration is something like testing1:version So when the for loop stops executing I get something like this in my .txt file.

testing1:version
kubernetes:version
node:version

And this is what I need, I can't figure out a better way to do this.

villanelle
  • 15
  • 4
  • Do you need it in both your variable AND your text file? Is that what you are asking. If so you can use `tee` like: `new_image=$(echo "$image:version" | cut -d '/' -f2 | tee -a list_images.txt)` `tee` will split stdout, in this case to append to the file AND stdout so it can be captured in your variable. – JNevill Apr 08 '22 at 14:16
  • You are passing the output to the variable `new_image`. So, `other_variable="$new_image"` would do what you asked. But seeing the expected output, that seems to me that is not what you meant. Also, I don't really understand your use of `cut` here. – Ljm Dullaart Apr 08 '22 at 15:40
  • @LjmDullaart When I `echo` the image name and tage, my output at first is `web/node:version` but `cut` would cut the string in such way that I get the remaining part of the string after delimiter `/` so I end up with `node:version`. I edited the post, I didn't realize I made a mistake there. – villanelle Apr 08 '22 at 15:57

1 Answers1

0

Using an answer, because the comments make it unreadable.

Do I understand correctly that you want:

for dir in $directories
do
        dockerfile=$(find ./repo/$dir -name "Dockerfile");
        docker build -f $dockerfile . -t $dir:version;
        echo "$dir:version" | cut -d '/' -f2
done > list_images.txt

or do you actually have a need for the variable(s) further-on in your script?

And

new_image=$(echo "$dir:version")
trimmed=${new_image#*/}

will do your cut in bash, but that's just for bonuspoints :-)

Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31