我正在使用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循环在一个子subshell中运行,$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
我想知道有没有办法解决这个问题?
https://stackoverflow.com/questions/56100973
复制相似问题