Tuesday, April 9, 2013

Linux/Unix Shell scripting: Select command examples

Select command is similar to for, while and until loops in Linux Shell scripting.

What is a select command?

Select is a Linux command useful for doing iterations indefinitely in shell scripts. This will come handy when you require user to select options depending on their requirements. With select command we can present some data/options to user for interactive Shell scripts. Depending on user inputs, Select command run that option and gives back you the prompt with options once again for selection one more time.

Syntax of Select command:

select VARNAME in list
do
Commands
done

in the above syntax, list can be

1)list of file names
2)list of values(constants)
3)A flower brace
4)A file content
5)A Linux/Unix command output.


etc.

Example

#!/bin/bash
select var1 in abc ced efg hij
do
echo "Present value of var1 is $var1"
done


Save the above file as selectexe.sh and start executing above script as shown below.
bash selectexe.sh
1) abc
2) ced
3) efg
4) hij
#? 1
Present value of var1 is abc
#? 2
Present value of var1 is ced
#? 3
Present value of var1 is efg
#? 4
Present value of var1 is hij
#?


If you see you are prompted with a prompt: ‘#?’, This is default prompt used by select which is assigned to PS3 variable. If you want to change this default prompt from #? to some other we can do that as well by defining PS3 before executing select command at the prompt or in script as shown below script.

#!/bin/bash
PS3='Please enter a number from above list: '
select var1 in abc ced efg hij
do
echo "Present value of var1 is $var1"
done


Save the above file to selctexe1.bash and start executing it

bash selectexe.sh
1) abc
2) ced
3) efg
4) hij
Please enter a number from above list: 2
Present value of var1 is ced
Please enter a number from above list: 3
Present value of var1 is efg
Please enter a number from above list:


If you see the difference the prompt got changed from default #? to “Please enter a number from above list:”

Know more about PS3 prompt here.

If you observe in my definition I mention select is a indefinite loop which will not terminate until we press ctrl-c. And more over from above shell script we cannot do much. We have to combine select command with case sentence to make deadly weapon and to give more control for you.

Combining select and case sentences

Syntax:

Select VARNAME in list
do
Case $VARNAME in
Opt1) commands;;
 Opt2) commands;;
 Opt3) commands;;
 *) exit;;
done
done


Here case sentence will solve the problem of pressing ctrl-C to come out of the loop, this can be done with *) option set in case sentence. This is short introduction of select command

0 comments:

Post a Comment