linux - 使用 bash 脚本循环遍历一堆变量
问题描述
我有 4 个域,我想每小时检查一次我的 cron。它检查一个单词是否存在,如果不存在,它将重新启动机器。在下面的示例中,我正在检查 4 个域,但是如何在 if 语句中循环遍历这些变量,而不必在我的 bash 脚本中复制 4 次。
#!/bin/bash
webserv1="domain1.com"
webserv2="domain2.com"
webserv3="domain3.com"
webserv4="domain4.com"
Keyword="helloworld" # enter the keyword for test content
if (curl -s "$webserv1" | grep "$keyword")
then
echo " the website is working fine"
else
sudo reboot
fi
if (curl -s "$webserv2" | grep "$keyword")
then
echo " the website is working fine"
else
sudo reboot
fi
if (curl -s "$webserv3" | grep "$keyword")
then
echo " the website is working fine"
else
sudo reboot
fi
if (curl -s "$webserv4" | grep "$keyword")
then
echo " the website is working fine"
else
sudo reboot
fi
解决方案
数组方法是:
arr=(a1.com a2.com a3.com) ## Define an array with values
#Loop through all the array values
for val in "${arr[@]}"
do
echo $val
done
输出将是:
a1.com
a2.com
a3.com
您的脚本将如下所示:
webservers=(domain1.com domain2.com domain3.com domain4.com)
Keyword="helloworld"
for webserver in "${webservers[@]}"
do
if (curl -s "$webserver" | grep "$keyword")
then
echo " the website $webserver is working fine"
else
sudo reboot
fi
done
推荐阅读
- python - 在熊猫数据框中找到一个值
- eclipse - 格式化程序配置文件存储在 Eclipse 中的什么位置?
- java - 从字符串初始化java int 2d数组
- python - 在使用带有约束和列表解构的泛型时,Mypy 无法确定类型
- android - Jetpack Compose TextField 中的 android:selectAllOnFocus
- android - OEM 是否可以将 CAN 总线事件共享到 Android Auto 应用程序?
- vue.js - 如何在 Vue JS 中制作一个允许其他组件继承新功能或代码的 Base 组件
- keycloak - 如何使用 keycloak 验证我的应用程序
- batch-file - 使用 WinSCP get 命令下载多种文件类型/扩展名
- php - Silverstripe 4 Zend 不见了