Sunday, January 11, 2015

goto in bash

GOTO is frowned upon. Bash simply removed goto. this causes problems, particularly if you do have a need to skip to a particular section of code. Web search turned up various people recommending the use of functions instead. This still doesn't solve the problem of non-local resumption.

Closest I found was Bob Copeland's approach: http://bobcopeland.com/blog/2012/10/goto-in-bash/

It's an interesting use of sed to much up the script up to the "label" and then executing the script. Very Neat trick. I wanted something simpler within Bash itself.

My problem is pretty much the same as Bob indicates on his web-page: i have a script that must process things in several steps, each of which is time consuming and can fail. Re-running prior steps is prohibitive, so I need some mechanism to resume from where the script last failed (or close to it).

So here's what I came up with:



#!/bin/bash

function usage() {
  echo "$0 [step]"
}

label=$1;
if [ -z "$label" ]; then  label="step1"; fi

# do all common setup here. This stuff will be done each time the script is run

while true; do
 echo processing step [$label]; # to give a hint about where to restart from
 case "$label" in
  "step1")
      # add processing for step1 here
      label="step2"
      ;;
  "step2")
      # add processing for step2 here
      label="step3"
      ;;
  "step3")
     # add processing for step3 here
      label="end"
      ;;
  "end") echo done; break;;
  *)
    usage
    exit
    ;;
 esac

done

Here's how it runs:
 # /tmp/test_goto.sh 
processing step [step1]
processing step [step2]
processing step [step3]
processing step [end]
done

 # /tmp/test_goto.sh step2
processing step [step2]
processing step [step3]
processing step [end]
done


No comments: