2

I want to run the following command in bash

ruby ......

The commands outputs the string "Created all things" when successful.

How can I run the command and check the output for the text Created all things to make sure it is successful so that I can run other commands using bash?

Rue Vitale
  • 1,549
  • 4
  • 17
  • 24
  • Your command should have a exit status of 0 if everything is successful, non-zero if not, so that you don't have to rely on any particular output. – chepner Dec 10 '15 at 20:03
  • BTW, if the only way to check whether your program was successful is reading its output, then it was poorly written. A well-behaved UNIX program indicates success or failure through exit status. – Charles Duffy Dec 10 '15 at 23:37
  • ...so, you could (if your Ruby program were well-behaved) do: `if ruby ....; then echo "Success"; else echo "Failed"; fi`, and not need to have your shell script look at its output at all. And if it's not well-behaved, that's a thing to complain to its authors about. – Charles Duffy Dec 10 '15 at 23:37

2 Answers2

1

You can save the output in a variable using the $(...) syntax, then do regular bash checks like:

output=$(ruby ....)
if [ "$output" = "Created all things" ]; then
    # success, keep going
else
    # failure, clean up
fi

Given your comment about wanting to see if it ended with that string, you can use a bash regex instead:

if [[ "$output" =~ Created\ all\ things$ ]]; then
...
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • problem is that is not the only output it returns. The command returns a lot of other output but at the end it returns "Created all things" if successful. So I need a regular expression – Rue Vitale Dec 10 '15 at 18:39
  • @PotaOnasys see my update that will hopefully address that – Eric Renouf Dec 10 '15 at 18:43
0

Similar to what Eric had written, but this will search for the string throughout the entire output instead of just the end.

results=$(ruby.......)
 if [[ $(echo ${results} | grep -c "Created all things") != "0" ]] ; then
    echo "Command appears to be successful"
 else
    echo "Command appears to have failed"
 fi
IT_User
  • 729
  • 9
  • 27