Plexus Plexus - 24 days ago 4x
Bash Question

A shell script (.sh) that calls an infinite loop called by another script to run in the background

Essentially what is happening is I'm operating on a limited instruction set framework (to run on an embedded device). The idea is very simple.

I call a script which makes two files:

  • file A: start_up - which calls the infinite loop

  • file B: background_while - which repeats a process over again

contents of file A:

sh background_while&

contents of file B:


while true
#some commands
sleep 5

I would like to terminate this process called in the background. Could someone show how this is best done using a keyboard interrupt?


If scriptA just ends after calling scriptB as a background then you cannot continue waiting for a keyboard interrupt. So, instead of immediately ending scriptA you can have a tight loop and wait for a signal, then kill your background processes by using trap.

Something like:



function kill_background(){
   kill ${myPid}

trap kill_background SIGINT

bash ./ &


Your scriptB will be the same. $! gets the pid of the last command executed (your scriptB) and wait makes scriptA wait for all background processes to return. trap will catch interrupt signals and kill your scriptB.