Sometimes you may want to check if a Docker volume exists or not in a Bash script:
if volumeExists $1; then
echo "volume exists"
else
echo "volume does not exist"
fi
To check existence of a Docker volume we can use the docker volume ls command with the name option but there are several caveats:
- it does not do an exact match and returns results that match on all or part of a volume’s name
- The output contains two columns
$ docker volume ls
DRIVER VOLUME NAME
local 0cbe8bb612d6d4c5727d1eb52b5a7a682088ab744181f7da9c1341e9fae83034
To just extract the last column we can use awk {print $NF} command:
$ docker volume ls | awk '{print $NF}'
NAME
0cbe8bb612d6d4c5727d1eb52b5a7a682088ab744181f7da9c1341e9fae83034
And to do an exact match we can further use grep -E option. The complete function looks like:
function volumeExists {
if [ "$(docker volume ls -f name=$1 | awk '{print $NF}' | grep -E '^'$1'$')" ]; then
return 0
else
return 1
fi
}
Remember in Bash 0 means success or true inside an if statement. Tip: do not use grep -w as it will match mysql-test when you want to search for mysql
awk always supercedes grep in functionality, so there is no need to pipe from awk to grep. And when you exit a bash function, it returns the exit code of the last command executed inside the function. Therefore you can reduce the function to:
function volumeExists(){
docker volume ls -f name=${1}|awk ‘BEGIN{f=1} $2==”‘${1}'”{f=0;exit} END{exit f}’
}