简体   繁体   中英

Shell scripts run one after another

I have 5 shell scripts. Each has a java command. Previous jobs output is input to the next job.

I created a superScript.sh

//mail - to inform beginning
sh script1.sh;
sh script2.sh;
sh script3.sh;
sh script4.sh;
sh script5.sh;
//mail to inform end

Sample script1.sh

cd toBaseDirectory;
java -cp /path/to/application.jar main.class parameter

But all the jobs are started at the same time. How can I make this sequential?

Try to run javas like this

java -cp /path/to/application.jar main.class parameter & wait

If want to run the second command only if the first exited successfully. To do so, join them with &&

command1 && command2

simple Example

~$ cat abc.sh 
#!/usr/bin/env bash
echo "hi"

~$ cat pqr.sh 
#!/usr/bin/env bash
echo "batman say :  $1"

If abc.sh execute successfully then only execute pqr.sh

~$ retval=$(./abc.sh) && result=$(./pqr.sh "$retval") && echo "$result"
batman say :  hi

you can also try similar approach with your java command execution using shell script

Note: To execute Shell scripts as command sequentially, waiting for the first to finish before the next one starts. You can use; command1; command2

wait waits for a process to finish

You can also choose to run the second command only if the first exited successfully. To do so, join them with &&

cmd1 && cmd2

but In repetitive cases like this I recommended using a simple loop in the body of your script:

for n in {1..5} ; do sh script${n}.sh ; done

The loop not only to run them in order but is easier to tweak and reuse when needed, with using brace expansion

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