linux - 检查条件并在 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
在这个脚本中,它只检查第一个条件。任何帮助,将不胜感激。谢谢!
解决方案
在这个脚本中,它只检查第一个条件
因为-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" ]]
推荐阅读
- sql-server - 从返回表的 SQL 存储过程中获取特定列的值
- mongodb - Spring Data MongoDB中的键集(Seek)分页
- javascript - 从网页中的 javascript 函数触发 Chrome 扩展
- javascript - JavaScript 基于多个数组过滤对象
- php - 如何从一个mysql表的日期时间字段中仅获取日期,合并相似的日期并通过cron作业更新另一个表
- javascript - Fetch URL 调用显示 Promise {
: “待办的” } - mysql - 当司机去度假时,卡车停在仓库里。修改表格设计以适应这一点:在需要删除的代码上标记 X
- c# - 401 来自一台设备的未经授权的错误,但来自另一台设备的成功
- css - 创建一个内容居中的 CSS 正方形,最好使用 Semantic-UI
- makefile - BSD Make 替换在规则 $(objdir)/%o 中失败:%c