循环访问所有数组成员

循环访问所有数组成员

我最近一直在玩脚本编写..在@Cas的帮助下写了这个

#!/bin/bash


## Variables ##

host="`/bin/hostname`";


    ## Limits ##

OneMin="1";
FiveMin="6";
FifteenMin="6";

    ## Mail IDs ##

To="[email protected], [email protected]";
Fr="root@"$host;


    ## Load Averages ##

LA=(`uptime | grep -Eo '[0-9]+\.[0-9]+' | cut -d"." -f1`)


    ## Top Process List ##

tp=(`ps -ef | sort -nrk 3,3 | grep -E "(php|httpd)" | grep -v root | head -n30 | awk '{print $2}'`)


## Actions ##

if [ ${LA[0]} -ge $OneMin ]; then


    ## Send Mail ##

echo -e "From: $Fr
To: $To
Subject: *ALERT* - Current Load on '$host' Is High
Load Averages Are:  \n\n
1:Min\t5:Min\t15:Min   \n
${LA[0]}\t${LA[1]}\t${LA[2]}  \n\n

List Of Processes That Were Killed \n" | sendmail -t


    ## Kill Top Pocesses ##


for i in $tp ; do
    kill -9 $i
done



fi

我不确定该数组是否有效,尤其是最后一部分,我添加了一个循环来终止顶级进程..因为它不会打印该电子邮件中的进程列表。我不知道为什么。但脚本没有给出任何错误..

好的 ## 解决方法 ##

顺便说一句,这行得通吗?

#!/bin/bash


## Variables ##

host="`/bin/hostname`";


    ## Limits ##

OneMin="7";
FiveMin="6";
FifteenMin="6";


    ## Load Averages ##

LA=(`uptime | grep -Eo '[0-9]+\.[0-9]+' | cut -d"." -f1`)



## Actions ##


    ## One Minut Action ##

if [ ${LA[0]} -ge $OneMin ]; then


    ## Send Mail ##

echo -e "From: $Fr
To: $To
Subject: *ALERT* - Current Load on '$host' Is High
Load Averages Are:  \n\n
1:Min\t5:Min\t15:Min   \n
${LA[0]}\t${LA[1]}\t${LA[2]}  \n\n

List Of Processes That Were Killed \n
`ps -ef | sort -nrk 3,3 | grep -E "(php|httpd)" | grep -v root | head -n30 | awk '{print $2}'`" | sendmail -t


    ## Kill Top Pocesses ##


for i in `ps -ef | sort -nrk 3,3 | grep -E "(php|httpd)" | grep -v root | head -n30 | awk '{print $2}'` ; do
    kill -9 $i
done


fi

我的意思是这会杀死所有 PiD 吗?

答案1

问题是tp=(...定义了一个数组,但$tp仅引用了该数组的第一个元素。

你需要

for i in "${tp[@]}" ; do

相关内容