List Only Docker Container IDs with docker ps -q
Print only container IDs with docker ps -q, or -aq for stopped ones too, and feed them to other commands. An empty list makes docker stop fail unless you use xargs -r.
You want a list of container IDs to pass to stop, remove or count.
docker run -d --name q-a alpine:3.20 sleep 60 > /dev/null
docker run -d --name q-b alpine:3.20 sleep 60 > /dev/null
docker create --name q-c alpine:3.20 > /dev/null
echo "running: $(docker ps -q --filter name=q- | wc -l | tr -d ' '), all: $(docker ps -aq --filter name=q- | wc -l | tr -d ' ')"
docker ps -q --filter name=q-a | tr -d '\n' | wc -c | tr -d ' '
docker stop $(docker ps -q --filter name=nothing) 2>&1 | head -n 1
docker ps -q --filter name=nothing | xargs -r docker stop
echo "xargs -r exit: $?"
docker ps -q --filter name=q- | xargs -r docker stop -t 0 | wc -l | tr -d ' '
docker rm -f q-a q-b q-c > /dev/nullrunning: 2, all: 3
12
docker: 'docker stop' requires at least 1 argument
xargs -r exit: 0
2-q prints one short ID per line, twelve characters, and -a adds containers that are not running. The run counted two running and three in total among the containers whose name started with q-. When the list is empty, docker stop $(docker ps -q) gets no arguments and fails with requires at least 1 argument. Piping into xargs -r skips the command when there is no input, and exited with status 0. See docker container ls.
xargs -r is a GNU option, and BSD xargs already skips empty input, though it accepts the flag. IDs can be ambiguous only if you shorten them yourself. Be careful with docker rm -f $(docker ps -aq), which removes every container on the host, including ones you did not start.