简体   繁体   中英

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

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 ie 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.

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM