一千萬個為什麽

搜索

Bash腳本:在腳本中查找最小值

I am writing a script that finds the minimum value in a string. The string is given to me with a cat and then I parse each number inside that string. The string only contains a set of numbers that is separated by spaced.

這是代碼:

echo $FREQUENCIES
for freq in $FREQUENCIES
do
    echo "Freq: $freq"
    if [ -z "$MINFREQ" ]
    then
        MINFREQ=$freq
        echo "Assigning MINFREQ for the first time with $freq"
    elif [ $MINFREQ -gt $freq ]
    then
        MINFREQ=$freq
        echo "Replacing MINFREQ with $freq"
    fi
done

這是我得到的輸出:

800000 700000 600000 550000 500000 250000 125000 
Freq: 800000
Assigning MINFREQ for the first time with 800000
Freq: 700000
Replacing MINFREQ with 700000
Freq: 600000
Replacing MINFREQ with 600000
Freq: 550000
Replacing MINFREQ with 550000
Freq: 500000
Replacing MINFREQ with 500000
Freq: 250000
Replacing MINFREQ with 250000
Freq: 125000
Replacing MINFREQ with 125000
Freq: 
: integer expression expected

問題是最後一行由於某種原因是空的或包含空格(我不知道為什麽)。我嘗試測試變量是否設置:if [-n“$ freq”]但是這個測試似乎在這裏沒有用,它仍然通過最後一行的if語句。

有人可以幫我弄清楚為什麽循環執行的最後一次,$ freq設置為空或空格以及如何避免這種情況?

編輯:

using od -c feeded with echo "<<$freq>>"

0000000   <   <   8   0   0   0   0   0   >   >  \n
0000013
0000000   <   <   7   0   0   0   0   0   >   >  \n
0000013
0000000   <   <   6   0   0   0   0   0   >   >  \n
0000013
0000000   <   <   5   5   0   0   0   0   >   >  \n
0000013
0000000   <   <   5   0   0   0   0   0   >   >  \n
0000013
0000000   <   <   2   5   0   0   0   0   >   >  \n
0000013
0000000   <   <   1   2   5   0   0   0   >   >  \n
0000013
0000000   <   <  \r   >   >  \n
0000006

似乎有一個額外的\ r \ n(來自文件)。

非常感謝你!

最佳答案

如果您只使用整數值,則可以使用正則表達式驗證字符串:

elif [[ $freq =~ ^[0-9]+$ && $MINFREQ -gt $freq ]]

轉載註明原文: Bash腳本:在腳本中查找最小值