Monday, February 27, 2012

Unix Tools - Shell Script Programming - Example - Demo_choice.sh

Demo_choice.sh

# Code :
#! /bin/bash

choice1() {
  printf "Disk usage for your HOME=%s\n" "${HOME}"
  du -sh ${HOME}
  return
}

choice2() {
  { printf "Press 'q' key to terminate viewing this list of files.\n";
    ls -lR ${HOME}; } | less
  return
}

choice3() {
  { printf "Press 'q' key to terminate viewing this list of files.\n";
  find ${HOME} -type f -size +1M -print | xargs ls -lh; } | less
  return
}

choice4() {
  read -p "Enter string for which to search:" STRING
  printf "Working...."
  find ${HOME} -type f ! -name '.seKreT' ! -name '*.flv' ! -name '*.mp4' -exec grep -l -- "${STRING}" {} \; >.seKreT
  printf "Done\n"
  { printf "Press 'q' key to terminate viewing this list of files.\n";
  cat .seKreT; } | less
  rm .seKreT
  return
}

menu() {
   local CHOICE
   local XIT=5 # this is the exit choice

   while true
   do
     printf "    M E N U\n"
     printf "1.  Display Disk Space Usage\n"
     printf "2.  Display File List\n"
     printf "3.  Display files >= 1MB in size\n"
     printf "4.  Display all files containing some string\n"
     printf "5.  Exit\n"
     read -p "Enter your choice:" CHOICE
     if [[ ! "${CHOICE}" =~ ^[0-9]+$ ]]
     then
       printf "You must enter an unsigned integer value between 1 and %d.\n" ${XIT}
       continue
     fi
     if ((CHOICE<1)) || ((CHOICE>XIT))
     then
       printf "Your choice must be between 1 and %d.\n" ${XIT}
       continue
     fi
     break
   done
   return ${CHOICE}
}

# main code
while true
do
  menu
  case ${?} in
    1) choice1 ;;
    2) choice2 ;;
    3) choice3 ;;
    4) choice4 ;;
    5) # do nothing, exit program
       break
       ;;
    *)
       # should never get here
       printf "Impossible choice; contact programmer now....\n"
       ;;
  esac
done
exit 0

Make permission for execution before running program
$chmod 700 Demo_choice.sh
$./Demo_choice.sh

No comments:

Post a Comment