meallhour meallhour - 2 months ago 24
Bash Question

How to loop through output of a command?

I have a command in a bash script which gives the following output

repository: docker/images
tags:
- 0.1-1
- 0.1-2
- 0.1-3
- 0.1-6
- 0.1-7
- 0.1-9


However, from the above output, I only need to browse through
0.1-1, 0.1-2 ...
and run a different command.

Please let me know how this can be achieved

Answer

Add a test to check if the line starts with - using grep:

... | grep '^-' | while read -r line; do echo "$line"; ## Do stuffs; done

As grep's output is buffered, you might want line buffering, need GNU grep:

... | grep --line-buffered '^-' | while ...; do ...; done

Or use stdbuf:

... | stdbuf -oL grep '^-' | while ...; do ...; done
Comments