maihabunash maihabunash - 1 year ago 132
Linux Question

Is it possible to set time out from bash script?

Sometimes my bash scripts are hanging and hold without clear reason

So they actually can hang for ever ( script process will run until I kill it )

Is it possible to combine in the bash script time out mechanism in order to exit from the program after for example ½ hour?

Answer Source

This Bash-only approach encapsulates all the timeout code inside your script by running a function as a background job to enforce the timeout:


Timeout=1800 # 30 minutes

function timeout_monitor() {
   sleep "$Timeout"
   kill "$1"

# start the timeout monitor in 
# background and pass the PID:
timeout_monitor "$$" &

# <your script here>

# kill timeout monitor when terminating:
kill "$Timeout_monitor_pid"

Note that the function will be executed in a separate process. Therefore the PID of the monitored process ($$) must be passed. I left out the usual parameter checking for the sake of brevity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download