簡體   English   中英

Bash - 使用從文件中讀取的條件中斷循環

[英]Bash - break the loop with a condition that is read from a file

我正在使用 bash 運行一些命令,直到它們達到我設置的目標。

這是我的代碼和解釋:

#!/bin/bash

#keep running some commands until a target is met
while : 
do
  #some executions that generate a number and write into flag.txt 

  #read the number from flag.txt and store in variable flag
  while read flag
  do
    echo $flag
  done <<< $(cat flag.txt)

  echo "hello $flag"

  #if the number from the file is >= the target I set (i.e. 0.717), then break the loop and finish the computation, otherwize, keep running.
  if [ $(echo "$flag >= 0.717" | bc) -eq 1 ]
  then
    break
  fi

done

我有一些錯誤:

0.7172
hello 
(standard_in) 1: syntax error
./test.sh: line 14: [: -eq: unary operator expected

我認為這是因為第二個 while 循環在子 shell 中運行,$flag 的值保留在第二個 while 循環中。

  do
    echo $flag
  done <<< $(cat flag.txt)

  echo "hello $flag"

為了證明這一點,如果我將 $flag 的值更改為實數:

if [ $(echo "0.72 >= 0.717" | bc) -eq 1 ]

然后我可以得到正確的結果:顯然,第二個 while 循環之外的 $flag 的值只是“空白”:

0.7172
hello 

我想知道是否有任何方法可以解決這個問題?

根據您的評論,聽起來您只需要替換:

  while read flag
  do
    echo $flag
  done <<< $(cat flag.txt)
  echo "hello $flag"
  if [ $(echo "$flag >= 0.717" | bc) -eq 1 ]; then
    break
  fi

和:

read flag < flag.txt
echo "hello $flag"
if test "$(echo "$flag >= 0.717" | bc)" -eq 1; then
    break
fi

使用 while 循環讀取文件中的每一行最終將flag設置為空字符串,因為循環不會終止,直到read到達文件末尾並將flag設置為空字符串。 請注意,假設echo "hello $flag"純粹用於調試,您可以簡單地執行以下操作:

if awk '{ exit ! ($1 >= .717)}' flag.txt; then break; fi

如果我正確理解您的問題,您應該將 if 語句放在嵌套循環中。 這樣它就可以在達到“目標”時打破。 您可以在滿足此條件時設置另一個標志,並使用該標志從外循環中跳出。

一元運算符錯誤是由於 $flag 沒有任何值,並且 if 語句僅計算第二個操作數。

暫無
暫無

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

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