March 14, 2011

Bash Scripting: Menu

Alright, I came across a note I had made for myself that is a basic outline of how I write simple text menus for my bash scripts when I need them. This easy piece of code was invaluable for piecing together my installer script for Ubuntu that installs all my software on a fresh install. I'll share my code with you so you can use it to your heart's content.
#!/bin/bash

#functions
#all your functions go in here

#menu
while :
do
cat << !
   1. First Item
   2. Second Item
   3. Third Item
   4. Exit
 !
echo -n "Choice?: "
read $choice
  case $choice in
   1) f_function1 ;;
   2) f_function2 ;;
   3) f_function3 ;;
   4) exit ;;
   *) echo "\"$choice\" is not valid"; sleep 2 ;;
  esac
done
This code creates a simple menu that shouldn't exit until you force it to or select the actual exit option. It is easy enough to add in extra options as you can just insert the new lines of code in and change the numbers accordingly.

No comments: