agarwal_achhnera agarwal_achhnera - 2 months ago 6x
Bash Question

how to capture command error message in variable for if block

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"
echo "not able to start service $i"


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"
   echo "service $i could not be started. Error: $error"

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.