Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell scripting: How can I stop a first program when the second will have finished?

I have two programs in Linux (shell scripts, for example):

NeverEnding.sh
AllwaysEnds.sh

The first one does never stop, so I wanna run it in background.
The second one does stop with no problem.

I would like to make a Linux shell script that calls them both, but automatically stops (kill, for example) the first when the second will have finished.

Specific command-line tools allowed, if needed.

like image 578
Sopalajo de Arrierez Avatar asked Mar 30 '14 22:03

Sopalajo de Arrierez


1 Answers

You can send the first into the background with & and get the PID of it by $!. Then after the second finishes in the foreground you can kill the first:

#!/bin/bash

NeverEnding.sh &
pid=$!

AllwaysEnds.sh

kill $pid

You don't actually need to save the pid in a variable, since $! only gets updated when you start a background process, it's just make it more easy to read.

like image 184
fejese Avatar answered Oct 18 '22 05:10

fejese