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
0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't this solution be affected by this bug ? As it is dated from 2010, I'm not sure wether it's been fixed
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.
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
+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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.