Something that I'd like to share with you!

Tuesday, April 20, 2021

Bash select - Creating simple menu with the Unix shell "select" loop

No comments :

Bash select command creates a menu from a list of items. The syntax is quite similar as the "for loop". Please refer to link below for more info https://linuxize.com/post/bash-select/ https://linuxhint.com/bash_select_command/ Lets do a quick test. Create a simple for loop as below and run it.
#!/bin/bash
for i in the quick brown fox jumps over the lazy dog
do
	echo $i
done
You will get a list of word as below.
# ./test.sh
the
quick
brown
fox
jumps
over
the
lazy
dog
Now modify the script as below. Replace "for" with "select". Add "break" just under the "echo" line.
#!/bin/bash
select i in the quick brown fox jumps over the lazy dog
do
	echo word selection = $i
	break
done
Now run the script and you will get below output.
# ./test.sh
1) the
2) quick
3) brown
4) fox
5) jumps
6) over
7) the
8) lazy
9) dog
#? 6
word selection = over
Note that, without "break", the script will keep on prompting the selection until you hit CTRL+C.

No comments :