Grim Edge
Grim Edge

Reputation: 27

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

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.

how can i refresh the value of $A0 every time while loops?

what i get now si the first value of $A0 perpetual witch is smaller than 2.37

it takes some time until the output of script.sh in $A0 becomes > 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

Basically what i want is to run scrip2.sh when the conditions in script.sh are met...

Any ideas?

Thank you!

Upvotes: 1

Views: 1800

Answers (1)

Flopp
Flopp

Reputation: 1947

Just put the computation of A0 inside the loop, and exit the loop when 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. You need a hack like

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

See How to compare two floating point numbers in Bash?

Upvotes: 1

Related Questions