I'm trying to chain various commands to automate a common docker process. This isn't a docker thing, it's more of a trying-to-automate-it-in-bash thing.
I can run:
docker ps | grep manager | cut -f -d ' '
which lists the current docker containers, singles out one that contains the word 'manager' and then grabs the first field which is the container id eg 3a5455f3ac72
I can then run:
docker inspect -f'{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}} 3a5455f3ac72
which gets the IP address of the docker container eg 172.18.0.4
What I would like to achieve is a variable called container_id and a variable called container_IP that I can use in bash scripts. I have tried:
container_id="docker ps | grep manager | cut -f 1 -d ' '"
container_ip='docker inspect -f'{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $container_id'
But when I try to create the container_id variable, I get:
invalid argument "1" for "-f, --filter" flag: bad format of filter (expected name=value)
See 'docker ps --help'.
I think I have an error in how I'm using single/double quotes, but I can't figure out where I'm going wrong.
CodePudding user response:
Your code could look like the following:
container_id() {
docker ps -f 'name=manager' --format '{{.ID}}'
}
container_ip() {
local id
id=$(container_id)
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$id"
}
container_ip
an error in how I'm using single/double quotes
Quotes do not matter here. Do not store commands as strings. Use functions to store commands. Remember to check your scripts with shellcheck. Also see http://mywiki.wooledge.org/BashFAQ/050 .
Creating variables from piped commands that contain single quotes
To create variables, execute the commands with command substitution. Instead of functions, you can just execute the commands:
container_id=$(docker ps | grep manager | cut -f 1 -d ' ')
container_ip=$(docker inspect -f'{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$container_id")
echo "$container_ip"