简体   繁体   English

将值与数组进行比较时Bash语法错误

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

I have the following arrays defined in a bash script 我在bash脚本中定义了以下数组

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

I read also two values from a file 我还从文件中读取了两个值

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

The values stored in the arrays and in start_time and end_time are epoch times, I mean values like 1361810326.840284000, 1361862515.600478000, 1361990369.166456000 数组中以及start_time和end_time中存储的值是纪元时间,我的意思是像1361810326.840284000、1361862515.600478000、1361990369.166456000

In the "..." line I want to compare the values of start_time and end_time with all the values stored in an array in the following way 在“ ...”行中,我想通过以下方式将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

However this code yields a syntax error. 但是,此代码会产生语法错误。 What am I doing wrong? 我究竟做错了什么?

If you are using POSIX shell-style comparisons, it is good practice to put each test in its own square brackets. 如果您使用的是POSIX Shell样式比较,则最好将每个测试放在自己的方括号中。 Also, you were missing a space from the end of the comparison. 此外,在比较结束时您还缺少一个空格。 Remember that ] is an argument to the function [ , rather than a syntactical construct: 请记住, ]是函数[的参数,而不是语法构造:

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

Same for the other one. 另一个也一样。 I have quoted your variables as it is a good habit to get into. 我已经引用了您的变量,因为这是一个好习惯。 I have also used a brace expansion rather than calling seq . 我还使用了大括号扩展而不是调用seq

If you are using bash, you can take advantage of the nicer arithmetic syntax: 如果您使用的是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