Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle errors in shell script

I am writing shell script to install my application. I have more number of commands in my script such as copy, unzip, move, if and so on. I want to know the error if any of the commands fails. Also I don't want to send exit codes other than zero.

Order of script installation(root-file.sh):-

./script-to-install-mongodb
./script-to-install-jdk8
./script-to-install-myapplicaiton

Sample script file:-

cp sourceDir destinationDir

unzip filename

if [ true] 
// success code
if

I want to know by using variable or any message if any of my scripts command failed in root-file.sh.

I don't want to write code to check every command status. Sometimes cp or mv command may fail due to invalid directory. At the end of script execution, I want to know all commands were executed successfully or error in it?

Is there a way to do it?

Note: I am using shell script not bash

like image 461
Galet Avatar asked Aug 02 '26 09:08

Galet


2 Answers

/* the status of your last command stores in special variable $?, you can define variable for $? doing export var=$? */

unzip filename
export unzipStatus=$?
./script1.sh
export script1Status=$?
if [ !["$unzipStatus" || "$script1Status"]]
     then                  
         echo "Everything successful!"       
     else
         echo "unsuccessful"
fi
like image 153
Uddhav P. Gautam Avatar answered Aug 04 '26 09:08

Uddhav P. Gautam


Well as you are using shell script to achieve this there's not much external tooling. So the default $? should be of help. You may want to check for retrieval value in between the script. The code will look like this:

./script_1
retval=$?
if $retval==0; then
  echo "script_1 successfully executed ..."
  continue
else; 
  echo "script_1 failed with error exit code !"
  break
fi
./script_2

Lemme know if this added any value to your scenario.

like image 20
jagatjyoti Avatar answered Aug 04 '26 08:08

jagatjyoti



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!