0

I have a script which links to a process in background. Now i want to run the 2nd script followed by 1st one ( which starts the background process) together.

Also is it possible to add an exit command at the end so that once the 2nd process is complete, the background process should exit automatically.

Example : script1

#!/bin/tcsh
#
background process &
#

once its running

script2:

#!/bin/tcsh
#
matlab <program.m>
#

End both the process when script 2 is completed. How??

Thanks in advance

1

I'm assuming when you state that you wish them to start "together" you mean in relative proximity to each other. For that just execute the scripts in the order you want one line after another.

#!/bin/bash
./script2.sh &
.script1.sh

To capture the end of the background process you'll want to store the PID of the first. To do this put the script process in the background and store $! to a local variable.

If you'd like to also kill the background process when you kill the foreground script you can use Bash's trap function. Pass in a function or a block of code you wish to execute and the signals you'd like to capture.

#!/bin/bash
./script2.sh &
SCRIPT_2_PID=$!
trap "kill $SCRIPT_2_PID; exit" SIGHUP SIGINT SIGTERM
./script1.sh

Please note that the trap function replaces the typical response to the signals provided so if you want the script to exit on CTRL+C you'll need to include the exit.

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.