Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a bash script line by line? [duplicate]

Tags:

bash

#Example Script
wget http://file1.com
cd /dir
wget http://file2.com
wget http://file3.com

I want to execute the bash script line by line and test the exit code ($?) of each execution and determine whether to proceed or not:

It basically means I need to add the following script below every line in the original script:

if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi

and the original script becomes:

#Example Script
wget http://file1.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
cd /dir
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
wget http://file2.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi
wget http://file3.com
if test $? -eq 0 
then
    echo "No error"
else
   echo "ERROR"
   exit
fi

But the script becomes bloated.

Is there a better method?

like image 495
J.Joe Avatar asked Jan 20 '26 11:01

J.Joe


1 Answers

One can use set -e but it's not without it's own pitfalls. Alternative one can bail out on errors:

command || exit 1

And an your if-statement can be written less verbose:

if command; then

The above is the same as:

command
if test "$?" -eq 0; then
like image 70
Andreas Louv Avatar answered Jan 22 '26 08:01

Andreas Louv