Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture command error message in variable for if block

Tags:

linux

bash

shell

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
like image 389
agarwal_achhnera Avatar asked Apr 29 '26 10:04

agarwal_achhnera


1 Answers

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.

like image 118
fedorqui 'SO stop harming' Avatar answered May 01 '26 02:05

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!