I would like to generate a synthetic docker ps
table but my docker image paths are very long. The solution I am trying to do is to display only the last part of the image name:
This is what I have:
docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Command}}"
NAMES IMAGE STATUS COMMAND
a_container a_local_image Up 36 minutes "python…"
another_container registry.example.com/group/subgroup/project/my_image:latest Up 38 minutes "go…"
I would like:
docker ps --format "table {{.Names}}\\t{{ <magic .Image> }}\\t{{.Status}}\\t{{.Command}}"
NAMES IMAGE STATUS COMMAND
a_container a_local_image Up 36 minutes "python…"
another_container my_image:latest Up 38 minutes "go…"
so basically, get what is after the last /
, like basename
does.
This is what I tried:
# No fixed length
docker ps --format "table {{ slice .Image 0 10}}"
# No last index available
docker ps --format 'table {{ (split "/" .Image) }}'
Any help or workaround is appreciated.
p.s.: since I use docker cli, I don't think I can define custom functions to use in the template expression.
CodePudding user response:
There is no good way to get the last element of a template array. Even though you can use index
and len
built-ins, you can't use arithmetic to get len - 1
.
This is a template-only trick:
{{ $image := "" }}{{ range split .Image "/" }}{{ $image = . }}{{ end }}{{ $image }}
Basically it does the following:
- declare a var
$image
split
the.Image
on/
- iterate over the array string and just assign to
$image
- at the end of the range,
$image
will hold the value of the last element - print
$image
Full command (with enclosing apex '
so you don't have to escape quotes):
docker ps --format 'table {{.Names}}\t{{ $image := "" }}{{ range split .Image "/" }}{{ $image = . }}{{ end }}{{ $image }}\t{{.Status}}\t{{.Command}}'
CodePudding user response:
You may could use next workaround, I put it in a shell file just because it's too long, but you are ok to call it directly in shell.
test.sh
paste <(docker ps --format 'table {{.ID}}') \
<(docker ps --format 'table {{.Image}}' | awk -F '/' '{print $NF}') \
<(docker ps --format 'table {{.Command}} {{.CreatedAt}} {{.Status}} {{.Ports}} {{.Names}}')
Explain:
docker ps --format 'table {{.ID}}'
get theID
column ofdocker ps
docker ps --format 'table {{.Image}}' | awk -F '/' '{print $NF}')
, frist get theImage
column, then useawk
to split/
, get the last sub column as you required.- the left is used to get remained columns as you needed of
docker ps
- Finally, use
paste
command to combine the output of above command.