4

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?

4
  • Wouldn't it make more sense to find the cause of the faulty behavior? Commented Mar 8, 2015 at 15:03
  • yes , but I want to know the time out option . Commented Mar 8, 2015 at 15:04
  • 1
    Well, make a launch wrapper: that wapper launches your script, takes its process id and uses that to register a cron job 30 minutes from now. The cron job executes a kill command on the process id. Commented Mar 8, 2015 at 15:09
  • hi Guys , can you post your answers so I will choose the most logical answer Commented Mar 8, 2015 at 15:50

2 Answers 2

13

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

#!/bin/bash

Timeout=1800 # 30 minutes

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

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Will the background process not keep the main process running? Meaning this will ALWAYS timeout, even if the script has executed in full?
@Alan: Yes it will always timeout. No, the main process will not remain running, but the background process will. If that is a problem for you, you could store the background process' PID from $! and kill it before terminating the main program. Or use an EXIT handler. Or use Gnu's timeout as rici suggested.
Ya - Good answer. Storing the timeout_monitor PID and killing it should do the job. Might think of incorporating this into your answer, it's one of the first that pops up on google. (I'm logging whether or not the script times out, so I need the background process to die if the script executes in full beforehand)
@Alan: Alright, followed your suggestion and added killing of the monitor.
11

If you have Gnu coreutils, you can use the timeout command:

timeout 1800s ./myscript

To check if the timeout occurred check the status code:

timeout 1800s ./myscript

if (($? == 124)); then
  echo "./myscript timed out after 30 minutes" >>/path/to/logfile
  exit 124
fi

1 Comment

is it possible to log something to a file whenever the timeout happens?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.