• Uncategorized

About linux : how-to-make-sure-first-command-finishes-and-then-only-execute-second-command-in-shell-script

Question Detail

how to make sure first command finishes and then only execute second command in shell script

#!/bin/sh
echo "Stopping application"
#command to stop application

echo "Starting application"
#command to start application

In above code, I wanted to make sure that command to stop application is finished properly and then only start the application.

How to handle this.

Please note in my case if application is already stopped then command to stop application takes some random time to complete i.e. 20sec, 30 sec .
So adding sleep is not proper way.

Main moto behind script is to restart application.
Considering fact that if application is allready stopped it doesnt work properly.

If application is running then the script works perfect.

Question Answer

You can use the command return code and a condition to do this.

#!/bin/sh
echo "Stopping application"
#command to stop application
rc=$?

# if the stop command was executed successfuly
if [ $rc == 0 ]; then 
    echo "Starting application"
    #command to start application
else
    echo "ERROR - return code: $rc"
fi

There are ‘exit codes’, try this:

ls
...

echo $?
0

than:

ls non_existing_file
ls: cannot access 'non_existing_file': No such file or directory

echo $?
2

This command echo $? prints exit code of previous command, if it’s 0 than it’s OK, all non 0 codes means some kind of error which is not OK.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.