首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Bash -使用从文件读取的条件中断循环

Bash -使用从文件读取的条件中断循环
EN

Stack Overflow用户
提问于 2019-05-12 23:56:49
回答 2查看 144关注 0票数 -1

我正在使用bash运行一些命令,直到它们达到我设置的目标。

下面是我的代码和解释:

代码语言:javascript
复制
#!/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

我得到了一些错误:

代码语言:javascript
复制
0.7172
hello 
(standard_in) 1: syntax error
./test.sh: line 14: [: -eq: unary operator expected

我认为这是因为第二个while循环在一个子subshell中运行,$flag的值保持在第二个while循环中。

代码语言:javascript
复制
  do
    echo $flag
  done <<< $(cat flag.txt)

  echo "hello $flag"

为了证明这一点,如果我将$flag的值更改为实数:

代码语言:javascript
复制
if [ $(echo "0.72 >= 0.717" | bc) -eq 1 ]

然后我可以得到正确的结果:显然,在第二个while循环之外的$flag的值是“空的”:

代码语言:javascript
复制
0.7172
hello 

我想知道有没有办法解决这个问题?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56100973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档