Automating a Process Using Phases
Problem
You have a long job or process you need to automate, but it may
require manual intervention and you need to be able to restart at
various points in the progress. You might use a GOTO
to jump
around, but bash doesn’t have that.
Solution
Use a case statement to break your script up into sections or phases.
First, we’ll define a standardized way to get answers from the user:
# cookbook filename: func_choice function choice { # Let the user make a choice about something and return a standardized # answer. How the default is handled and what happens next is up to # the if/then after the choice in main local answer printf "%b" "\a" # Ring the bell read -p "$*" answer case "$answer" in [yY1] ) choice='y';; [nN0] ) choice='n';; * ) choice="$answer";; esac } # end of function choice
Then, we’ll set up our phases:
# cookbook filename: using_phases # Main Loop until [ "$phase" = "Finished." ]; do case $phase in phase0 ) ThisPhase=0 NextPhase="$(( $ThisPhase + 1 ))" echo '############################################' echo "Phase$ThisPhase = Initialization of FooBarBaz build" # Things that should only be initialized at the beginning of a # new build cycle go here # ... echo "Phase${ThisPhase}=Ending" phase="phase$NextPhase" ;; # ... phase20 ) ThisPhase=20 NextPhase="$(( $ThisPhase + 1 ))" echo '############################################' echo "Phase$ThisPhase = Main processing for FooBarBaz build" # ... choice "[P$ThisPhase] Do we need to stop and fix anything? ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.