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?
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
You can store the id in a variable that you can use in next command.
res=$(docker load ...)
id=${res:25:12}
docker tag $id ...
This gets a substring from offset 25 (I hope I counted correctly) with length 12
Edit: I found out, you dont even need sed to extract the hash in a "clean" way.
res=$(docker load ...)
hash=${res##*sha256:}
id=${hash:0:12}
docker tag $id ...
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