LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash Scripting: Menu from file (https://www.linuxquestions.org/questions/programming-9/bash-scripting-menu-from-file-883408/)

sociopathichaze 05-29-2011 06:50 PM

Bash Scripting: Menu from file
 
I have a file called list.txt with on word on each line that changes in length. I'd like to make a menu, each line being its own choice. I pieced together most of it the only thing missing is a failsafe for typing a number out of range. Any ideas?

Code:

#!/bin/bash
p=`cat list.txt | awk '{print$1}'`

select CHOICE in $p
do
echo $CHOICE
done


David the H. 05-29-2011 11:24 PM

First of all, $(..) is highly recommended over `..`.

Second, awk can take a filename as an input argument, so you don't need to use cat and a pipe. And if there's only one word per line, then you don't need $1.
Code:

awk '{print}' list.txt
Third, using awk here is truly overkill anyway. cat alone does exactly the same thing as the above command. Even better, just use a simple < shell redirection. You can even put it directly in the select command and skip the variable.
Code:


p=$( cat list.txt )
#or
p=$( <list.txt )
#or
select CHOICE in $( <list.txt ); do

Fourth, an invalid choice in select results in an empty variable. So simply add a test of some kind after the read to check whether it contains anything. If empty, then just let it loop again (or do whatever you want it to do), else issue a break command to exit the loop (or again, whatever). case statements are used most often here, but any conditional construct will do.
Code:

#!/bin/bash

select CHOICE in $( <list.txt ) ; do

  case $CHOICE in

      "") echo "Not a valid choice."
          echo "Try again." ;;

      *)  echo "$CHOICE"
          break ;;

  esac

done

exit 0


AnanthaP 05-30-2011 09:47 PM

Pseudo code:
Code:

a=wc -l filename
choice=-1
while choice < 1 and > $a
do
display menu and choose
if choice > 0 and <= a then
do <what you got to do>
else
error message
fi
next choice
done



All times are GMT -5. The time now is 05:28 PM.