简体   繁体   English

检查 bash 中的条件并运行命令

[英]Check the condition and run commands in bash

I am need of running series of commands after checking the conditions.检查条件后,我需要运行一系列命令。 I tried this我试过这个

#var1 results in output active or inactive
var1= systemctl is-active docker


#Function for enabling and running the docker service

function run {
echo "Starting Docker service.."
sudo systemctl enable docker
sudo systemctl start docker
mkdir /mnt/new/hello_test
}

# Checking whether the docker service is up or not

if [[ $var1 -eq inactive ]]
        then
        echo "$(run)"
else
        echo "Docker service is  running..." ; touch /mnt/new/testingg;
fi

In this script, it is only checking 1st condition.在这个脚本中,它只检查第一个条件。 ANy help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

In this script, it is only checking 1st condition在这个脚本中,它只检查第一个条件

Because -eq is for numbers.因为-eq用于数字。 Both sides [[ <this> -eq <that> ]] are converted to numbers. [[ <this> -eq <that> ]]两边都转换为数字。 Because they are not numbers but strings active and inactive , they are interpreted as variable names and because these variables are not defined, both sides are equal zero.因为它们不是数字而是字符串activeinactive ,所以它们被解释为变量名,并且因为这些变量没有定义,所以两边都等于零。

But forget it, just execute the actual command in if :但是忘了它,只需在if中执行实际命令:

run() {
   echo "Starting Docker service.."
   sudo systemctl enable docker
   sudo systemctl start docker
   mkdir /mnt/new/hello_test
}

if ! systemctl is-active -q docker; then
        run
else
        echo "Docker service is  running..."
        touch /mnt/new/testingg;
fi

Anyway to compare strings, use = :无论如何要比较字符串,请使用=

[[ "stringone" = "stringsecond" ]]
# like:
var1=$(systemctl is-active docker)
[[ "$var1" = "inactive" ]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM