我正在使用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
我想知道有没有办法解决这个问题?
发布于 2019-05-13 02:10:39
根据你的评论,听起来你只需要替换:
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
发布于 2019-05-13 00:39:15
如果我没理解错你的问题,你应该把If语句放在嵌套循环中。这样它就可以在达到“目标”时中断。当满足此条件时,您可以设置另一个标志,并使用该标志从外部循环中断。
一元运算符错误是由于$flag没有任何值,并且if语句只计算第二个操作数。
https://stackoverflow.com/questions/56100973
复制相似问题