Skip to content

Instantly share code, notes, and snippets.

@rhysrhaven
Last active December 17, 2022 13:21
Show Gist options
  • Save rhysrhaven/7549226 to your computer and use it in GitHub Desktop.
Save rhysrhaven/7549226 to your computer and use it in GitHub Desktop.
Simple bash state machine to re-run script in the same place after failure. Better to use case statement fall through if you have Bash 4.
#!/bin/bash
LOL=/tmp/LOLZ
RUNNING=true
while $RUNNING; do
case $([ -f $LOL ] && cat $LOL) in
INIT)
echo "Reached INIT State. Moving to WORK state."
echo "WORK" > $LOL
;;
WORK)
echo "Reached WORK State."
if [ ! -f /tmp/PASS ]; then
echo "Simulating failure. Touch /tmp/PASS to fix."
exit 1
fi
echo "BREAK" > $LOL
;;
BREAK)
echo "Reaching BREAK State. Getting out of loop."
RUNNING=false
;;
*)
echo "file doesn't exist, creating init state"
echo "INIT" > $LOL
;;
esac
done
echo "Script finished successfully."
exit 0
@hotpocket
Copy link

this was helpful for me thank you

@xxxludixxx
Copy link

It also helped me a lot, even though it didn't work on current version of bash. Feel free to check out my implementation of bash stack/state machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment