Execute two statements with a small difference between them

I often run these statements:

docker stop $(docker ps -aq); docker rm $(docker ps -aq)

What’s the shortest way to type this? I tried

docker {stop, rm} $(docker ps -aq)

but that doesn’t expand to two separate statements.

Asked By: k314159

||

Using history expansion:

docker stop $(docker ps -aq)
!:0 rm !:2*

or

docker stop $(docker ps -aq)
^stop^rm

The shortest way to is to create a function that runs both commands, put that in your shell’s startup files and then use that.

e.g.

dstoprm() {
    docker stop $(docker ps -aq)
    docker rm $(docker ps -aq)
}

(Even shorter if you make the function have a one-letter name.)


To reduce repetition at the cost of boilerplate, you could use a loop:

for action in stop rm; do docker $action $(docker ps -aq); done

or to create multiple commands with brace expansion, you could do something like this, not that I’m seriously suggesting anyone to use this:

eval 'docker '{stop,rm}' $(docker ps -aq);'
Answered By: ilkkachu

Starting with:

docker stop $(docker ps -aq); docker rm $(docker ps -aq)

what if we capture the docker ps -aq into a variable, so as not to calculate it twice? It’s expected to be the same value: all containers. If that were to change, we would be running rm on a different set of containers from the ones on which we invoked stop:

d=$(docker ps -aq); docker stop $d; docker rm $d

We have achieved shortening the command sequence and ensuring it operates on the same set of containers.

Answered By: Kaz

Use the -f argument to force removal.

docker rm -f $(docker ps -aq)

This will stop and remove the container in a single command. Adding -v will also remove anonymous volumes belonging to the container.

Answered By: Gerald Schneider
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.