Friday, December 3, 2010

shell script state machine

The basic structure of a shell script state machine is an endless loop with a case branch structure inside that responds to a current state variable. To end the loop "break" out of the while loop.

state="start"
while true; do
  case "$state" in 
  "start")       
    echo "initial state"
    state="next"
    ;;
  "next") 
    echo "next state"
    state="done"
    ;;
  "done") 
    echo "done"
    break
    ;;
  *)
    echo "invalid state \"$state\""
    break
    ;;
  esac
done

running the above state machine prints
initial state
next state
done

This structure is useful for programs that are easier to express using a flow chart (state chart) than a linear structure, such as an interactive script with retry options.

No comments:

Post a Comment