I'm trying to get the docker image id for a certain image so I do
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
123456789012.dkr.ecr.us-east-1.amazonaws.com/some-name1 60 4a625fb9a2a4 5 hours ago 3.97GB
987654321012.dkr.ecr.us-east-1.amazonaws.com/some-other-name2 365 59b27e46effc 6 days ago 3.98GB
I expect this to give me the image id, i.e., 4a625fb9a2a4 in this case...
$ docker image ls | grep name1 | cut -d " " -f3
...but it doesn't, it gives a blank. What am I missing?
This NEEDS to be a simple shell script so I can embed it in a Groovy script in a Jenkinsfile pipeline.
Because you have several " " between each data.
Easier way is to strip whitespaces to a single space and cut:
docker image ls | grep name1 | tr -s ' ' | cut -d " " -f 3
EDIT: chepner's answer is to prefere, but I let this one live since original question was "why".
The best thing to do is let docker images ls do all the work, instead of parsing its default output.
$ docker image ls --filter "reference=*name1*" -q
4a625fb9a2a4
--filter replaces your grep command, and -q replaces cut. There is also a --format option for more precise control over the output, but -q is effectively just a shortcut for --format '{{.ID}}'.
If, for whatever reason, --filter doesn't do what you need, you can always use --format to produce output that is more easily parsed by other commands.
I think that awk is better for splitting up columnar output. For example:
$ docker image ls | awk '/fedora/ {print $3}'
cc510acfcd70
5292e27c6dac
422dc563ca32
Alternately, you could reform the output using --format to work better with cut:
$ docker image ls --format '{{ .Repository }} {{ .ID }}' | grep fedora | cut -d" " -f2
cc510acfcd70
5292e27c6dac
422dc563ca32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With