Bash – How should I idle until I get a signal?

Thom Smith picture Thom Smith · Dec 1, 2011 · Viewed 9k times · Source

I have a script for launchd to run that starts a server, then tells it to exit gracefully when launchd kills it off (which should be at shutdown). My question: what is the appropriate, idiomatic way to tell the script to idle until it gets the signal? Should I just use a while-true-sleep-1 loop, or is there a better way to do this?

#!/bin/bash

cd "`dirname "$0"`"

trap "./serverctl stop" TERM
./serverctl start

# wait to receive TERM signal.

Answer

rosenfeld picture rosenfeld · Aug 24, 2016

You can simply use "sleep infinity". If you want to perform more actions on shutdown and don't want to create a function for that, an alternative could be:

#!/bin/bash
sleep infinity & PID=$!
trap "kill $PID" INT TERM

echo starting
# commands to start your services go here

wait

# commands to shutdown your services go here
echo exited

Another alternative to "sleep infinity" (it seems busybox doesn't support it for example) could be "tail -fn0 $0" for example.