Skip to content
Advertisement

Bash get docker image ID automatically

I’m trying to run a few docker commands in my linux machine:

1- sudo docker load -i test.tar
2- sudo docker tag bf46cff9b182 test:v1.0
3- sudo docker run -it --network host -v /home/logs:/home/test/test/logs test:v1.0

But I would like to make a runme.sh and execute all in one run. The problem is that ImageID bf46cff9b182 is dynamiccally changing everytime. So I need to somehow pipe it from the output of the load command, which is in fact possible.

The output of load is like this:

Loaded image ID: sha256:bf46cff9b1829b50e28f6485c923efff94799dd84cbf747dc86f6e5d006f2a81

On Linux it is shown as this:

4f512fb4b0ea: Loading layer  5.079MB/5.079MB
Loaded image ID: sha256:b6c3df68a9365ccb0935a835aa332b29db780cb7e81eac83acf717b2                                                                             de779073

And the 12 characters after sha256 would be bf46cff9b182, which would me my Image ID inserted in command #2 above.

How can I write a bash command to do this automatically?

Advertisement

Answer

Here’s a simple sed script to extract the sha256.

docker load -i test.tar |
sed -n 's/^Loaded image ID: sha256:([0-9a-f]*).*/1/p'

You can now capture this into a variable, or pipe it onward with xargs:

docker load -i test.tar |
sed -n 's/^Loaded image ID: sha256:([0-9a-f]*).*/1/p' |
xargs -i docker tag {} test:v1.0
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement