Mike D
Mike D

Reputation: 365

How to run a loop in bash to match a string and execute another command ONCE

Here's what I'm trying to accomplish. I want to run a loop until a string is matched, execute a do command ONCE and move on to the rest of the script? For example

string=`tail /var/myapp/main.log|sort -k5 | awk '{print $4}'`

while [ $string = "failed" ] do
service restart myapp
break
done
echo "blah blah blah as the rest of the script"
echo "on and on"

I've tried using until, but I doubt that's the one. Maybe I'm not using the correct command. "IF" won't work because I want to run this once a day until it finds what I'm looking for at a specific time, do its thing, do the rest of the script, and be done. No matter how much I try, it will continue to loop through... forever. I just want it to do it once.

Upvotes: 0

Views: 3520

Answers (2)

devnull
devnull

Reputation: 123458

You need to check for the condition within an infinite loop and break out when it satisfies your criteria:

while true; do
  string=$(tail /var/myapp/main.log|sort -k5 | awk '{print $4}')
  [ $string = "failed" ] && break
done
service restart myapp
echo "blah blah blah as the rest of the script"
echo "on and on"

Upvotes: 1

Zombo
Zombo

Reputation: 1

while sleep 1
do
  set $(tail /var/myapp/main.log | sort -k5 | awk '{print $4}')
  [ $1 = failed ] || break
done

service restart myapp
  • loop every second
  • every loop check if output equal failed
  • if not failed then break
  • rest of script

Upvotes: 0

Related Questions