我想生成一个合成的
docker ps
表,但我的docker图像路径很长。我尝试做的解决方案是仅显示图像名称的最后一部分:
这就是我所拥有的:
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…"
我想要:
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…"
所以基本上,获取最后一个
/
之后的内容,就像basename
一样。
这是我尝试过的:
# No fixed length
docker ps --format "table {{ slice .Image 0 10}}"
# No last index available
docker ps --format 'table {{ (split "/" .Image) }}'
任何帮助或解决方法表示赞赏。
p.s.:由于我使用 docker cli,我认为我无法定义在模板表达式中使用的自定义函数。
没有好的方法来获取模板数组的最后一个元素。即使您可以使用
index
和 len
内置函数,您也不能使用算术来获得 len - 1
。
这是一个仅模板的技巧:
{{ $image := "" }}{{ range split .Image "/" }}{{ $image = . }}{{ end }}{{ $image }}
基本上它会执行以下操作:
$image
split
.Image
上 /
$image
$image
将保存最后一个元素的值$image
完整命令(带有封闭的顶点
'
,这样你就不必转义引号):
docker ps --format 'table {{.Names}}\t{{ $image := "" }}{{ range split .Image "/" }}{{ $image = . }}{{ end }}{{ $image }}\t{{.Status}}\t{{.Command}}'
你可以使用下一个解决方法,我把它放在一个shell文件中只是因为它太长了,但是你可以直接在shell中调用它。
测试.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}}')
解释一下:
docker ps --format 'table {{.ID}}'
获取 ID
的
docker ps
docker ps --format 'table {{.Image}}' | awk -F '/' '{print $NF}')
,首先获取Image
列,然后使用awk
拆分/
,根据需要获取最后一个子列。docker ps
paste
命令合并上述命令的输出。可以调整建议的仅模板技巧来保留标题。
--format 选项 Go 模板中的 split 函数在处理标题文本时返回
string
类型。对于其余行,它返回 []string
类型。尝试将范围函数应用于字符串失败,导致所有后续标头被删除。可以通过检查预期的标题文本来保留标题。
docker ps --format 'table {{.Names}}\t{{ if eq "IMAGE" .Image }}{{ .Image }}{{ else }}{{ $image := "" }}{{ range split .Image "/" }}{{ $image = . }}{{ end }}{{ $image }}{{ end }}\t{{.Status}}\t{{.Command}}'