簡體   English   中英

在bash腳本中將變量與浮點數進行比較時[:缺少`]'錯誤

[英][: missing `]' error while comparing variables with floating point numbers in a bash script

temp.txt是帶有一行的文件:

1.2034 3.2323 4.3121 5.1223

我必須使用不同的值多次執行以下一組操作,所以所有這些都在一個循環中。 以下是我面臨的主要問題,希望能幫助您解決。


v1=$(cut -d" " -f2 temp.txt);

v2=$(cut -d" " -f3 temp.txt);

v3=$(cut -d" " -f4 temp.txt);

v4=$(cut -d" " -f5 temp.txt);


#$v1, $v2, $v3, $v4 contain the above 4 values (1.2034, 3.2323, 4.3121, 5.1223). I have verified that. I want to compare their values, but when I do, I get an error because of incorrect syntax.

if [ "$v1" -gt "$v2" | bc ] && [ "$v3" -gt "$v4" | bc ]; then

    echo Yes

fi

我收到此錯誤:

line 6: [: missing `]'

File ] is unavailable.

有人可以幫我語法嗎? 我已經嘗試了幾種不同的方法,但是沒有用。 我嘗試了括號和空格的不同組合,並且都使用bc和不使用bc

您想要構造一個有效的bc表達式並將其通過管道傳遞給bc ,捕獲輸出,然后將與預期結果進行比較。

if [[ $(echo "$v1 > $v2" | bc) == 1  &&  $(echo "$v3 > $v4" | bc) == 1 ]]; then
  echo Yes
fi

如果bash可以進行浮點運算(或者您的值實際上是整數),則可以直接在bash進行比較:

if [[ $v1 -gt $v2 && $v3 -gt $v4 ]]; then echo Yes; fi

要么

if (( v1 > v2 && v3 > v4 )); then echo Yes; fi

填充四個變量的更快方法是

read x1 v1 v2 v3 v4 x2 < temp.txt

x1x2只是我們實際上並不關心其值的變量;第一個字段以及在第5個thone之后可能出現的任何字段。)

暫無
暫無

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

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