首页 > 解决方案 > 使用 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

标签: linuxbashshellscripting

解决方案


数组方法是:

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

推荐阅读