How to check if docker machine exists programmatically?

6.7k views Asked by At

I'm using docker-machine to manage my cloud servers. I'm writing some bash scripts to automate some tasks. The question is: "How to check in bash script if docker machine with the specific name already exists?". I need some expression to return true if it exists and false if it doesn't.

Thanks

3

There are 3 answers

1
Adrian Mouat On

Just run it through grep, if a regexp is good enough for you. For example if you have a machine called foo:

$ docker-machine ls -q | grep '^foo$'

Should work and return 0. The caret matches the start of the line and the space avoids partial matches. If it doesn't match you will get a non-zero return code.

1
Yogesh_D On

Not a scripting guru but I would do a "docker-machine help", if this command runs and the exit code ($?) is zero, the docker-machine executable is available and functioning. If the return code is 127 (typically this returned by bash for command not found) or anything other than non-zero, you can assume that either docker-machine is not installed or is not running properly.

1
Luís Bianchin On

You can use something like the following:

docker-machine status some-machine 2> /dev/null || echo "Machine does not exists"