Sunday, March 30, 2008

Creating menus using select - BASH


The select construct is adopted from the Korn Shell and is a good tool for building menus.

The basic usage:

select variable [in list]
do
command...
break
done

This prompts the user to enter one of the choices presented in the variable list.

Note: select uses the PS3 prompt by default.

A simple script to start with.

$ cat se3.sh
#!/bin/bash

PS3='Your Favourite Shell ?' # Set the prompt string
echo
select shell
do
echo
echo "You have selected: $shell"
echo
break #This break is important and must
done
exit 0

Executing:
$ ./se1.sh

1) ksh
2) bash
3) sh
4) zsh
5) csh
Your Favourite Shell ?2

You have selected: bash

List is omitted:
If "in list" is not mentioned, select picks the list of command line arguments ($@) passed to the script or to the function in which the select construct is embedded. See "se3.sh" script below:

$ cat se3.sh
#!/bin/bash

PS3='Your Favourite Shell ?' # Set the prompt string
echo
select shell
do
echo
echo "You have selected: $shell"
echo
break #This break is important and must
done
exit 0

Executing:
$ ./se3.sh bash ksh zsh

1) bash
2) ksh
3) zsh
Your Favourite Shell ?1

You have selected: bash


Using select in a function:

$ cat se6.sh
#!/bin/bash

PS3='Your Favourite Shell ?' # Set the prompt string
echo

f_choose () {
select shell
do
echo
echo "You have selected: $shell"
echo
break #This break is important and must
done
}

f_choose "bash" "ksh" "csh" "zsh"
exit 0

Executing:
$ ./se6.sh

1) bash
2) ksh
3) csh
4) zsh
Your Favourite Shell ?3

You have selected: csh


A practical example:

$ cat sel.sh
#!/bin/bash

f_Add () {
echo "Inside Add Function"
}

f_Delete () {
echo "Inside Delete Function"
}

f_Update () {
echo "Inside Update Function"
}

PS3='Your Menu ? ' # Set the prompt string
echo
select item in "Add" "Delete" "Update" "quit"
do

#Handling default case in select
if ! test "$item"; then
echo "Wrong entry, try again"
continue
fi

[ $item = "quit" ] && exit 0

echo
echo "You have selected: $item"
f_$item # Calling the function
echo
done
exit 0

Executing:
$ ./sel.sh

1) Add
2) Delete
3) Update
4) quit
Your Menu ? 1

You have selected: Add
Inside Add Function

Your Menu ? 2

You have selected: Delete
Inside Delete Function

Your Menu ? 3

You have selected: Update
Inside Update Function

Your Menu ? 5
Wrong entry, try again
Your Menu ? 4

No comments:

© Jadu Saikia www.UNIXCL.com