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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With