Using 'select' for multiple choices in shell scripts

I found this neat construct in the gnu bash reference. Select is a great way to be able to present a list of options to a user in a shell script.

Take the example given in the reference:

select fname in *;
do
	echo you picked $fname \($REPLY\)
	break;
done

This outputs:

1) Applications                   6) Library                      11) User Guides And Information  16) bin                          21) mach_kernel                  26) tmp
2) Desktop DB                     7) Network                      12) Users                        17) dev                          22) mnt                          27) upnp.log
3) Desktop DF                     \8) Parallels                    13) VMware Images                18) etc                          23) private                      28) usr
4) Developer                      9) Public                       14) Volumes                      19) mach                         24) sbin                         29) var
5) Fonts Folder                  10) System                       15) automount                    20) mach.sym                     25) sw
#? 

Now if you type the number of one of the options e.g. 10 you'll see the following:

you picked System (10)

As you can see in this example fname is set to the item in the list selected. The special var REPLY contains the number of the reply. Now to be able to use this in a script we would need to know when something other than one of the list items is selected. In this case the var fname will be set to null which can simply be tested with the -z switch in an if statement like so:

if [ -z $fname ]; then
    echo 'Your selection was invalid'
fi

To learn more about shell-scripting in general then I would certainly recommend checking out Classic Shell Scripting.

Show Comments