bash脚本结束循环如果为true

时间:2014-03-29 16:52:12

标签: arrays bash

我有一组数字(1 2 3 4 5)

magicnumber=7

我想说,如果幻数等于数组中找到的数字或大于数组中的最高数字那么。

{array [@]} - 包含数字

highnum=the highest number from the array

for f in $dir   "#f is file with a number in it"
do 

    "the number inside file f is pulled out and named filenum"
    filenum

    for i in ${array[@]}
    do
        if [ $i -eq $filenum ] || [ $filenum -gt $highnum ]
        then 
            do this and end the "for i loop"
        else
            continue with loop
        fi
    done
done

1 个答案:

答案 0 :(得分:3)

您可以使用"数组字符串化"和模式匹配以确定幻数是否在数组中 - 下面的所有引号和空格都是非常慎重和必要的。

if [[ " ${array[*]} " == *" $magicnumber "* ]]; then
    echo "magic number is in array"
else
    # Otherwise, find the maximum value in the array 
    max=${array[0]}
    for (( i=1; i<${#array[@]}; i++ )); do
        (( ${array[i]} > max )) && max=${array[i]}
    done
    (( magicnumber > max )) && echo "magic number greater than array elements"
fi