0

This question already has an answer here:

I executed a command in a shell script and the command ends with "completed successfully" or "completed unsuccessfully". How can I read that in the script and use it for if and else conditions?

marked as duplicate by G-Man, αғsнιη, jasonwryan, cas, Kusalananda bash Jan 29 '18 at 7:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Does the command also set a reasonable exit status, or does it lie to the shell and say it succeeded when completing unsuccessfully? (Check $?) If the command isn't a liar, you can just use if <command>; then <stuff>; else <other stuff>; fi – Fox Jan 29 '18 at 3:53
  • It's not really a duplicate of "assign command outputs to a var". OP may need to WATCH the output WHILE the command is running. – Bach Lien Jan 29 '18 at 7:54
0

Try this:

your_command | \
tee >(sleep; [[ `tail -n1` =~ 'completed successfully' ]] && echo OK || echo NOTOK)

Explanation:

  1. tee: split your_command outputs into two (i) >(...) and (ii) stdout
  2. sleep: (optionally) wait for 1 second, change 1s to what you need
  3. tail -n1: extract last line
  4. =~: matching test; change the test to what you need
  5. echo OK, echo NOTOK: just examples, change to what you need
-2

I tested for both successfull and unsuccessfull scenario and worked fine

Below one is for successfull test

#!/bin/bash
pwd=====>Mention the command as per requirement
i=`echo $?`
if [[ $i == 0 ]]
then
echo "successfully"
else
echo "unsuccessfully"
fi

output

successfully

Below one is for Unsuccessfull test

#!/bin/bash
praveen ===> Command will fail so output will be unsuccessfull
i=`echo $?`
if [[ $i == 0 ]]
then
echo "successfully"
else
echo "unsuccessfull"
fi

output

unsuccessfull
  • This does not capture the text of the command as the OP wanted to do. Also, there's no need to set a variable to the result of echo $?, i=$? works. This too is not needed as if somecommand; then also work just fine. Additionally, the second line of both scripts contains syntax errors. – Kusalananda Jan 29 '18 at 7:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.