I am using if/then/elif/then/else Construct using exit codes to automate docker installation using below script but its failing at just line no 6. I tried all combinations but its not moving to 'elif' condition.
Please Help. Appreciate your support. Thanks in Advance.
1 #!/bin/bash
2
3 systemctl status docker
4
5 if [ $? -gt 0 ]; then
6 systemctl start docker
7 elif [ $? -eq 5 ]; then
8 rpm -qa docker*
9 elif [ $? -eq 0 ]; then
10 yum install -y docker
11 else
12 echo "docker cant be installed"
13 fi
OUTPUT: sh -x docker_check.sh
- systemctl status docker Unit docker.service could not be found.
- '[' 4 -gt 0 ']'
- systemctl start docker Failed to start docker.service: Unit docker.service not found.
Expecting that the script install docker as it is not install in my VM.
CodePudding user response:
Based on the output you provided, the exit status is 4 which means docker isn't installed. This causes the first condition to be true, so it tries to start docker and it fails. I'm not sure why you're installing docker when the exit status is 0 since that means success, but you need to install docker when the exit status is 4. This should work:
#!/bin/bash
systemctl status docker
if [ $? -eq 0 ] || [ $? -eq 4 ]; then
yum install -y docker
elif [ $? -eq 5 ]; then
rpm -qa docker*
elif [ $? -gt 0 ]; then
systemctl start docker
else
echo "docker cant be installed"
fi