簡體   English   中英

將值與數組進行比較時Bash語法錯誤

[英]Bash syntax error when comparing a value with an array

我在bash腳本中定義了以下數組

IFS=, read -r -a start_files <<< $(head -n 1 file.txt)
IFS=, read -r -a end_files <<< $(tail -n 1 file.txt)

我還從文件中讀取了兩個值

micro=1000000
IFS=#

[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read start_time end_time
do

    start_time=$(bc <<< "scale=6; $start_time/$micro")
    end_time=$(bc <<< "scale=6; $end_time/$micro")

    ...

done < $INPUT
IFS=$OLDIFS

數組中以及start_time和end_time中存儲的值是紀元時間,我的意思是像1361810326.840284000、1361862515.600478000、1361990369.166456000

在“ ...”行中,我想通過以下方式將start_time和end_time的值與數組中存儲的所有值進行比較

for i in `seq 0 116`;
do
    if [ $start_time -ge ${start_files[$i]} && $start_time -le ${end_files[$i]}]; then
        startF=$i
    fi        
done


for j in `seq 0 116`;
do
    if [ $end_time -ge ${start_files[$j]} && $end_time -le ${end_files[$j]}]; then
        endF = $j
    fi        
done

但是,此代碼會產生語法錯誤。 我究竟做錯了什么?

如果您使用的是POSIX Shell樣式比較,則最好將每個測試放在自己的方括號中。 此外,在比較結束時您還缺少一個空格。 請記住, ]是函數[的參數,而不是語法構造:

for i in {0..116}; do
    if [ "$start_time" -ge "${start_files[$i]}" ] && [ "$start_time" -le "${end_files[$i]}" ]; then
        startF="$i"
    fi        
done

另一個也一樣。 我已經引用了您的變量,因為這是一個好習慣。 我還使用了大括號擴展而不是調用seq

如果您使用的是bash,則可以利用更好的算術語法:

for ((i=0; i<=116; ++i)); do
    if (( start_time >= ${start_files[$i]} && start_time <= ${end_files[$i]} )); then
        startF="$i"
    fi        
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM