-2

I need to check if container is already present with specific name. Using if statement for same, however container is present with same name but i am not sure why if statement is not running successfully.

if [`echo password | sudo -S docker ps -all|grep test|cut -d' ' -f1`]
then
statements
else
statements

container with test name is present but its always going inside the else statement. Could you help me on this.

J.vik
  • 103
  • 2
  • 11
  • 3
    Possible duplicate of [Why should there be a space after '\[' and before '\]' in Bash?](https://stackoverflow.com/q/9581064/608639) – jww Nov 26 '18 at 09:28
  • Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Nov 26 '18 at 09:28

2 Answers2

2

You need blanks between [, ] and `, i.e. :

if [ `echo password | sudo -S docker ps -all|grep test|cut -d' ' -f1` ]

Also, you need fi after the last line.

0

in addition to @ÔHARA Kazutaka information.

-all does not exists, try --all instead.

The --quiet --filter name=test options are going to make docker filters output using the container's name, and make it prints to the standard output the CONTAINER ID if a container exists.

Give a try to this:

container_name=test

container_id=$(echo password | sudo -S docker ps --all --quiet --filter name="${container_name}")

if [ ! -z "${container_id}" ] ; then
  printf "%s is the id of the container with name '%s'\n" "${container_id}" "${container_name}"
else
  printf "no docker container with name '%s' has been found.\n" "${container_name}"
fi
Jay jargot
  • 2,745
  • 1
  • 11
  • 14