1

completely new to bash so any assistance is much appreciated. I'm looking for a script to do the following, its a pretty simple script but I cant seem to get it:

  • I want to run a command, this command will return either successful or some other string in the output.
  • if the output does not contain the word successful I want it to sleep for 5min and run again until it does contain successful.

It would look something like this

until (SOMECOMMAND) &> /dev/null
do
    if(SOMECOMMAND contains successful);
    break;
    else sleep 300
done

echo -e "\nThe command was successful."
1
  • sleep 5 (in your code) would sleep for 5 seconds while the text says "sleep for 5 min" -- please edit your post and change one or the other.
    – Jeff Schaller
    Jan 24, 2020 at 15:30

2 Answers 2

3

You could do something like:

#!/bin/bash

output=
count=0

until [[ $output =~ successful ]]; do
    output=$(somecommand 2>&1)
    ((count++))
    sleep 300
done

printf '\n%s\n' "Command completed successfully after $count attempts."

This will check if output contains successful, if you want to check that the output is exactly "successful" you can change the =~ to ==.

$( ... ) is command substitution which is being used to set the parameter output to the...output of somecommand.

3
  • Thank you this worked like a charm! just for my understanding why are we setting output to equal nothing?
    – Minz
    Jan 29, 2020 at 9:30
  • Also what does the 2>&1 do?
    – Minz
    Jan 29, 2020 at 9:39
  • @Minz: That redirects stderr to stdout, which is the same as &> that you have in your question but more portable.
    – jesse_b
    Jan 29, 2020 at 14:06
2

To run some-command until it outputs the string "successful" to stdout, sleeping five minutes after a failed run:

until some-command | grep -q successful
do
  sleep $((60 * 5)) ### or "sleep 5m", if supported by your version of sleep
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .