Command like 'docker ps' is a good tool to check on your running container/s. This is visually pleasant if you do not have many containers. What if you have hundreds of containers, and you just want to print just the names of the containers, or even better the names and id of the containers?
We can use --format flag in this situation. This flag is available on pretty much every docker commands that produce some kind of output to stdout, so that you can filter what you want to see as the output.
To use this flag, you just need to follow below format:
$ docker ps --format '{{json .Names}}'
"hardcore_carson"
whereby ".Name" is the field that you want to be displayed. For example, you want to list out just the ID of all the running containers, you can use:
$ docker ps --format '{{json .ID}}'
"e914bd4963d4"
You can see that the field is different from the displayed field name without the --format flag.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e914bd4963d4 alpine "/bin/sh" 29 minutes ago Up 29 minutes hardcore_carson
To know which flag is available to be used:
$ docker ps --format '{{json .}}'
{"Command":"\"/bin/sh\"","CreatedAt":"2021-05-08 11:32:12 +0800 +08","ID":"e914bd4963d4","Image":"alpine","Labels":"","LocalVolumes":"0","Mounts":"","Names":"hardcore_carson","Networks":"bridge","Ports":"","RunningFor":"33 minutes ago","Size":"0B (virtual 5.61MB)","State":"running","Status":"Up 33 minutes"}
To list 2 (or more) fields:
$ docker ps --format '{{json .ID}} {{json .Names}}'
"e914bd4963d4" "hardcore_carson"
You can also use the --format without the json keyword, the only different is the output would not be double quoted (which is not easy on the eyes if you have many fields)
$ docker ps --format '{{.ID}} {{.Names}}'
e914bd4963d4 hardcore_carson