简体   繁体   English

与while循环,直到动态条件满足bash脚本

[英]Bash script with while loop until dynamic conditions are met

#!/bin/bash
/home/user/script.sh > output.txt
VAR0=$(cat output.txt | grep -A 3 "word")
A0=$(echo $VAR0 | awk 'BEGIN { FS = "[:X]" } {printf $3}')
while [ $A0 \< 2.37 ] 
do echo $A0
sleep 10
done
/home/user/script2.sh

what i want to do is to run the script2.sh when the output of script.sh in output.txt is > 2.37 我想做的是当output.txt中script.sh的输出> 2.37时运行script2.sh

the issue is, the output of script.sh is dynamic so every time while loops it has to take a fresh output from output.txt until the condition is met and script2.sh can be run. 问题是,script.sh的输出是动态的,因此每次循环时,它都必须从output.txt中获取新的输出,直到满足条件并可以运行script2.sh。

how can i refresh the value of $A0 every time while loops? 每次循环时如何刷新$ A0的值?

what i get now si the first value of $A0 perpetual witch is smaller than 2.37 我现在得到的结果是,永久性女巫$ A0的第一个值小于2.37

it takes some time until the output of script.sh in $A0 becomes > 2.37 $ A0中script.sh的输出变为> 2.37会花费一些时间。

i have already considered doing 我已经考虑过

/home/user/script.sh
sleep 180
/home/user/script2.sh

but 3 min is too much and the change in output.txt can happen anywhere between 2 and 3 min 但是3分钟太多了,output.txt中的更改可能会在2至3分钟之间发生

Basically what i want is to run scrip2.sh when the conditions in script.sh are met... 基本上我想要的是在满足script.sh中的条件时运行scrip2.sh ...

Any ideas? 有任何想法吗?

Thank you! 谢谢!

Just put the computation of A0 inside the loop, and exit the loop when A0 >= 2.37 : 只需将A0的计算放入循环中,并在A0 >= 2.37时退出循环:

#!/bin/bash

while true ; do
    /home/user/script.sh > output.txt
    VAR0=$(cat output.txt | grep -A 3 "word")
    A0=$(echo $VAR0 | awk 'BEGIN { FS = "[:X]" } {printf $3}')
    echo $A0
    if (( $(echo "$A0 >= 2.37" | bc -l) )) ; then
        break
    fi
    sleep 10
done

/home/user/script2.sh

Note that bash can't compare floating point numbers by itself. 请注意,bash不能单独比较浮点数。 You need a hack like 你需要像

if (( $(echo "$A0 >= 2.37" | bc -l) )) ; then

See How to compare two floating point numbers in Bash? 请参阅如何在Bash中比较两个浮点数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM