Last Updated: December 27, 2018
·
70
· themichael'tips

Apply timeout on your bash code

Here a new Design Pattern that I've used to add timeout over bash code.

Instead to have a bad code like this:


function execute_cmd() {
ret=0
count=0
while [ "$ret" -ne "X" ]; do
   ret=`__code__`

  #this check could also be done by sleep command, but it's not good at all putting sleep:
  #the process could spend time to wait a resource that may be ready!!
   ((count++)
   if [ "$count" -gt "1000" ]; then
      echo "CMD IS NOT YET COMPUTED";
      exit -1
   fi
done
}

execute_cmd

We could re-think the design in something much more elegant and efficient :

#!/bin/bash
SCRIPT=$(readlink -f $0)

#First: separate the business code to the checks (functional or requirement code)
#in a dedicate code unit
function execute_cmd() {
ret=0
while [ "$ret" -ne "X" ]; do
   ret=`__code__`
done
}

#Second: use the right pattern - timeout command - to assign the maximum execution time we accept to wait
function timeout_execute_cmd() {
if ! timeout 10 $SCRIPT COMPUTE_CMD; then
    echo "CMD IS NOT YET COMPUTED"
    exit -1
fi
}

for param in "$@"; do
   if [ $param == 'COMPUTE_CMD' ];then
        compute_cmd
        exit 0
   fi
done

#Use timeout_exec_cmd istead of exec_cmd
timeout_exec_cmd

Enjoy!