IF条件由bash中的实数组成的间隔

时间:2014-07-10 05:03:46

标签: bash

这是一个bash例程,用于比较两个数字和一些由整数数字给定的定义区间:

#!/bin/bash

# The comparing function
function compareInterval {
 t1=$1
 t2=$2

 shift 2

 while (( "$2" )); do
     if ((  $t1 >= $1  &&  $t2 <= $2 )); then
         # got match
         return 0
     fi
 shift 2
 done

 return 1
}

# sample values
t_initial=2
t_final=4

# Invocation. Compares against 1-3, 3-5, 2-5
if compareInterval  $t_initial $t_final  1 3  3 5  2 5; then
    echo Got match
fi

如果间隔是由实数给出的,即1.234,那么函数中的条件如何变化?

2 个答案:

答案 0 :(得分:1)

这是代码的新版本:

#!/bin/bash

function compareInterval {
 t1=$1
 t2=$2

 shift 2

while (( $(awk -v var="$2" 'BEGIN{ if (var=="") print 0; else print 1; }') )); do
     var1=$(awk -v t1="$t1" -v t2="$1" 'BEGIN{ print (t1 >= t2) }')
     var2=$(awk -v t3="$t2" -v t4="$2" 'BEGIN{ print (t3 <= t4) }')
     if [[  "$var1" -eq "1"  &&  "$var2" -eq "1" ]]; then
         # got match
         return 0
     fi
 shift 2
 done

 return 1
}


t_initial=4399.75148230007220954256
t_final=4399.75172111932808454256
if compareInterval $t_initial $t_final 4399.48390124308 4400.47652912846 3 5 2 5; then
    echo Got match
fi

答案 1 :(得分:0)

另一个纯粹的bash解决方案:

#!/bin/bash

function compareInterval {
    t1=$1 t2=$2
    shift 2

    while [[ $# -ge 2 ]]; do
        is_ge "$t1" "$1" && is_le "$t2" "$2" && return 0  ## Got match.
        shift 2
    done
    return 1
}

function is_ge {
    local A1 A2 B1 B2

    if [[ $1 == *.* ]]; then
        A1=${1%%.*}
        A2=${1##*.}
    else
        A1=$1
        A2=0
    fi

    if [[ $2 == *.* ]]; then
        B1=${2%%.*}
        B2=${2##*.}
    else
        B1=$2
        B2=0
    fi

    (( L = ${#A2} > ${#B2} ? ${#A2} : ${#B2} ))

    A2=$A2'00000000000000000000'; A2=1${A2:0:L}
    B2=$B2'00000000000000000000'; B2=1${B2:0:L}

    (( A1 == B1 ? A2 >= B2 : A1 > B1 ))
}

function is_le {
    local A1 A2 B1 B2

    if [[ $1 == *.* ]]; then
        A1=${1%%.*}
        A2=${1##*.}
    else
        A1=$1
        A2=0
    fi

    if [[ $2 == *.* ]]; then
        B1=${2%%.*}
        B2=${2##*.}
    else
        B1=$2
        B2=0
    fi

    (( L = ${#A2} > ${#B2} ? ${#A2} : ${#B2} ))

    A2=$A2'00000000000000000000'; A2=1${A2:0:L}
    B2=$B2'00000000000000000000'; B2=1${B2:0:L}

    (( A1 == B1 ? A2 <= B2 : A1 < B1 ))
}

t_initial=2.4
t_final=4.5

if compareInterval "$t_initial" "$t_final" 1 3 3 5 2 5; then
    echo 'Got match.'
fi

注意:当然可以添加健全性检查,但我发现现在不太必要。