If you are concerned about shellcheck SC2046 (in which case you would receive a warning for the command docker stop $(docker ps -a -q)
) and you are using Bash4+ (to be able to use the mapfile
builtin command), you can run the following to stop all containers:
mapfile -t list < <(docker ps -q)
[[ ${#list[@]} -gt 0 ]] && docker container stop "${list[@]}"
The reasoning:
docker ps -q
returns all active containers ids
mapfile
stores the resulting container ids in the list
array
[[ ${#list[@]} -gt 0 ]]
tests if the list
array has 1 or more elements to execute the next command
docker container stop "${list[@]}"
stops all containers whose ids are stored in the list
array (will only run if the array has items)
Similarly, to remove all stopped containers:
mapfile -t list < <(docker ps -aq)
[[ ${#list[@]} -gt 0 ]] && docker container rm "${list[@]}"
(docker ps -aq
returns all container ids, even from stopped containers)
If you want to stop and remove all containers, you can run the above commands sequentially (first stop
, then rm
).
Alternatively, you can run only the the commands to remove the containers with rm --force
, but keep in mind that this will send SIGKILL, so running stop
first and then rm
is advisable (stop
sends SIGTERM, unless it times out, in which case it sends SIGKILL).