首页 > 解决方案 > 检查条件并在 bash 中运行命令

问题描述

检查条件后,我需要运行一系列命令。我试过这个

#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

在这个脚本中,它只检查第一个条件。任何帮助,将不胜感激。谢谢!

标签: linuxbashdockershellif-statement

解决方案


在这个脚本中,它只检查第一个条件

因为-eq是为了数字。两边[[ <this> -eq <that> ]]都转换为数字。因为它们不是数字而是字符串active,并且inactive它们被解释为变量名,并且因为这些变量没有定义,所以两边都等于零。

但是忘了它,只需执行以下实际命令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

无论如何要比较字符串,请使用=

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

推荐阅读