1

From my script I am running following commands:

 SCRIPT_1="ksh -x script1.sh & ksh -x script2.sh";
 SCRIPT_2="ksh -x script3.sh & ksh -x script4.sh";
 eval $SCRIPT_1;
 sleep 20s;
 eval $SCRIPT_2;

I want to only execute the $SCRIPT_2 after the $SCRIPT_1 completes. But currently they both getting executed at the same time regardless of they are being executed in separate lines.

Any idea on how to wait for the other script to finish before executing the next one?

  • 2
    Just use wait to wait for all the background jobs. – Stéphane Chazelas Dec 17 '14 at 15:58
  • 1
    See help wait. – goldilocks Dec 17 '14 at 15:58
  • That code runs script1.sh in the background but script2.sh in the foreground. Is that intended? The scripts of $SCRIPT_1 shall run in parallel and after all of them have finished those of $SCRIPT_2 shall run in parallel? – Hauke Laging Dec 17 '14 at 15:59
  • @HaukeLaging yes that's correct. – Sas Dec 17 '14 at 16:01
1
SCRIPT_1="ksh -x script1.sh & bg_pid=$!; ksh -x script2.sh; wait $bg_pid";
SCRIPT_2="ksh -x script3.sh & bg_pid=$!; ksh -x script4.sh; wait $bg_pid";
eval $SCRIPT_1;
sleep 20s;
eval $SCRIPT_2;
  • guess I wasn't clear. My problem is that I need to run String "$SCRIPT_1" first using eval command and then run the String "$SCRIPT_2" sequentially. – Sas Dec 17 '14 at 15:54
  • Can't you use ps to check script is still in process? I'm not sure using ksh, but in bash, I guess you can use: if [[ $(ps auxww | grep -i "script1.sh" | wc -l) -gt 1 ]] || [[ $(ps auxww | grep -i "script2.sh" | wc -l) -gt 1 ]]; then echo "Still in process "; else echo "Process SCRIPT_1 ended" ; fi; Maybe you should adapt it to ksh. Not sure. – Albert Dec 17 '14 at 16:05
  • 1
    @Albert You should rather use jobs (in bash; I am not familiar with ksh) for checking for background jobs. But wait is the superior approach anyway. – Hauke Laging Dec 17 '14 at 16:15
  • @HaukeLaging I'm quite sure. ps is the only way I knew to check if a process is running. Did not even know commands can be run using & concatenated. Not even the meaning of "$!". Now I know (after goggling... xD) – Albert Dec 17 '14 at 16:23
  • @Albert In the general case it is faster to just check whether /proc/$PID exists: if [ -d /proc/12345 ]; then echo yes; else echo no; fi – Hauke Laging Dec 17 '14 at 16:28
0

Using GNU Parallel you would do something like:

parallel ksh -x ::: script1.sh script2.sh
parallel ksh -x ::: script3.sh script4.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.