How to do it...

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 trapkill, and signals, we can set timers or alarms (ALRM) to perform clean exits from runaway functions or commands. Let's begin:

  1. 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 ...

Get Bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.