Bash alias for removing docker images does not use force flag

Currently I have an alias to force remove images, the command is something like:

docker rmi $(docker images | grep pattern | grep -v other_pattern | tr -s ' ' | cut -d ' ' -f 3) -f

Within my ~/.bashrc it looks like:

rm_images="docker rmi $(docker images | grep pattern | grep -v other_pattern | tr -s ' ' | cut -d ' ' -f 3) -f"

However when executed I get the following:

Error response from daemon: conflict: unable to delete <image_id> (must be forced) - image is referenced in multiple repositories
Asked By: jkgfinai

||

First, you should probably follow the syntax in the original documentation, which is docker rmi -f <images>.

Also, when defining an alias, you should use single quotes to evaluate the expression each time the alias is run. If you use double quotes (as you indicated in your question), the expression is only evaluated when the alias is defined (also see here).

So define your alias as follows (considering that your command substitution is correct):

alias rm_images='docker rmi -f $(docker images | grep pattern | grep -v other_pattern | tr -s " " | cut -d " " -f 3)'

Note how each single quote inside your command substitution has now been replaced with double quotes, which will work just as well for these commands.

Finally, you might consider using awk instead of a combined tr and cut, since awk handles contiguous whitespaces correctly without the need to trim first (also see my old question here).

Answered By: Artur Meinild
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.