I build a bash script to verify if certain container exists or not. If there is no input, it complains. Does your mind helping me?
#!/bin/bash
if [[ $# -eq 0 ]]
then echo "Docker container ID not supplied"
elif [[ docker images | grep -q $1 ]]
then echo "No such container $1"
else
echo $1
fi;
Edit:
A common output for docker images is the sample below. In case the token matches the 12 input characters and no more, the container indeed exists.
REPOSITORY TAG IMAGE ID CREATED SIZE
sappio latest 091f1bf3491c About an hour ago 556MB
postgres 11.4 53912975086f 3 years ago 312MB
node 7.7.2-alpine 95b4a6de40c3 5 years ago 59.2MB
The use cases for this shell script are:
1.
input: bash has_contained_id.sh
output: Docker container ID not supplied
input: bash has_contained_id.sh 1
output: "No such container 1"
input: bash has_contained_id.sh 091f1bf3491
output: "No such container 091f1bf3491"
input: bash has_contained_id.sh 091f1bf3491c
output: "091f1bf3491c"
CodePudding user response:
Assuming OP is receiving an error like:
./testme: line 9: conditional binary operator expected
./testme: line 9: syntax error near `images'
./testme: line 9: `elif [[ docker images | grep -q $1 ]]`
Then OP may want to consider the following modification:
# replace this:
elif [[ docker images | grep -q $1 ]]
# with this:
elif docker images | grep -q "$1"
Taking into consideration OP's additional requirements to match on an exact container name, and switching the echo
calls for the elif
and else
blocks:
if [[ $# -eq 0 ]]; then
echo "Docker container ID not supplied"
elif docker images | grep -qw "$1"; then
echo "$1"
else
echo "No such container $1"
fi
CodePudding user response:
With @markp-fuso I am able to achieve the shell script below:
#!/bin/bash
if [[ $# -eq 0 ]];
then echo "Docker container ID not supplied"
elif docker images | grep -qw "$1"; then
len=$(expr length "$1")
if [[ "$len" -eq "12" ]]; then
echo $1
else
echo "No such container $1"
fi;
else
echo "No such container $1"
fi;