3

Hi below is my code for bash shell script, in this I want to capture error message for if clause, when it says either job is already running or unable to start the job to a variable, how it is possible in below script, or any other way for the below functionality

if initctl start $i  ; then
    echo "service $i  started by script"
else
    echo "not able to start service $i"
fi
agarwal_achhnera
  • 2,582
  • 9
  • 55
  • 84

2 Answers2

8

You can for example use the syntax msg=$(command 2>&1 1>/dev/null) to redirect stderr to stdout after redirecting stdout to /dev/null. This way, it will just store stderr:

error=$(initctl start $i 2>&1 1>/dev/null)
if [ $? -eq 0 ]; then
   echo "service $i started by script"
else
   echo "service $i could not be started. Error: $error"
fi

This uses How to pipe stderr, and not stdout?, so that it catches stderr from initctl start $i and stores in $error variable.

Then, $? contains the return code of the command, as seen in How to check if a command succeeded?. If 0, it succeeded; otherwise, some errors happened.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Wouldn't this solution be affected by [this bug](https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/552786) ? As it is dated from 2010, I'm not sure wether it's been fixed – Aserre Aug 14 '14 at 09:05
  • Interesting... I wasn't aware of that. I don't have Ubuntu here with me, so we'll have to see if it works to the OP. Reading from the bug page, it doesn't seem to have been fixed. – fedorqui Aug 14 '14 at 09:29
  • 1
    Well, I have a 14.04 Ubuntu VM laying around and just tested your script. It works just fine, I was able to start `cron` and it returned the correct error when `cron` was already running. It does need `sudo` to run though, otherwise it returns an `Unknown job: xxx` error – Aserre Aug 14 '14 at 09:40
  • 1
    +1 And in case OP also wants to see `stdout` if successful, he could do `out=$(initctl start $i 2>&1)` and use for both. – John B Aug 14 '14 at 09:46
2

Use '$?' variable It stores any exit_code from the previous statement See http://www.tldp.org/LDP/abs/html/exitcodes.html for more information

initctl start $i
retval=$?
if [ $retval -eq 0 ]; then
    echo "service $i  started by script"
else
    echo "not able to start service $i"
fi
rurouni88
  • 1,165
  • 5
  • 10