We begin this recipe knowing that there is a command called timeout available to the Bash shell. However, it falls short of being able to provide the functionality of timeouts in functions within a script itself. Using trap, kill, and signals, we can set timers or alarms (ALRM) to perform clean exits from runaway functions or commands. Let's begin:
- Open a new terminal and create a new script by the name of mytimeout.sh with the following contents:
#!/bin/bashSUBPID=0function func_timer() { trap "clean_up" SIGALRM sleep $1& wait kill -s SIGALRM $$}function clean_up() { trap - ALRM kill -s SIGALRM $SUBPID kill $! 2>/dev/null}# Call function for timer & notice we record the job's PIDfunc_timer $1& SUBPID=$!# Shift the parameters ...