Linux Blog

Select Statements in Bash

Filed under: Shell Script Sundays — TheLinuxBlog.com at 10:40 pm on Sunday, August 19, 2007

Shell scripts often need a menu so that the user can interact with the script and choose options. An easy way to so this is with the “select” statement.

Syntax:

select selection_var [in list]; do
statements (can use selection_var)
done

Example:

echo "########################################";
echo "#  SELECTS EXAMPLE - TheLinuxBlog.Com  #";
echo "########################################";
echo "#        Please Choose an Option       #";
echo "########################################";
 
select selection_var in Number_1 This_is_Choice_2 Exit; do
case $selection_var in
Number_1 )
echo "You picked $selection_var or #$REPLY"
;;
This_is_Choice_2 )
echo "You picked $selection_var or #$REPLY"
;;
Exit )
echo Goodbye!
break
;;
* )
echo "Invalid Selection"
;;
esac
done

This bash select example has three choices. The first two are just examples, the third exits the script. There is a fourth case but it is not a choice, it tells the user that they have entered an invalid selection. I recommend using a case inside of a select because it will make life easier when adding onto a script. The $REPLY variable is returned from the select statement as a means of knowing what number was pressed. The $REPLY variable can be used in the case statement but I avoid doing so as all of the case blocks will have to be rearranged every time a new option is added.

The select statement in bash is very easy to implement and it can add a whole new range of functionality into your scripts. So try them out and look out for them in future shell scripts from The Linux Blog.





Random Man Pages:
vgagl
uptime
tty
blocktube

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>