2014-10-28 128 views
0

我已經在存儲在所述一個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和d 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 

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

+0

參數的命令需要通過例如分離空間。 – 2014-10-28 17:08:57

+3

如果您在問題中指出了您的語法錯誤,這將會很有幫助。 – 2014-10-28 17:09:26

+2

您在測試'''結束'之前缺少一個空格。 – 2014-10-28 17:09:34

回答

1

如果您使用的是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