Hi Gurus,
Is there a way to replace case -- esac with an array
while [ 1 ] ; do
read key_press ;
case $key_press in
p|P)
fun_P
;;
t|T)
fun_T
;;
l|L)
fun_L
;;
*)
fun_Misc
;;
esac
done
I want to replace case with an array...
Jagpreet
You can use associative array functionality of bash, not sure which version supports it, mine is 4.2.25
declare -A choice
choice[p]=fun_P
choice[P]=fun_P
read key_press
eval ${choice[$key_press]}
Assuming fun_P is a valid function defined.
HTH
--ahamed
thanks for reply ahamed.
first of all bash version
GNU bash, version 3.00.16(1)-release (sparc-sun-solaris2.10)
After assigning all the array fields.
whatever keypress entered it takes last choice.
I changed sequence as well, it takes the last assigned key to array for execution.
choice[a]=fun_a
choice=fun_b
choice[c]=fun_c
now at any key press it executes fun_c
one more point.. how do I take care of * case
case
*)
fun_misc
jagpreet
You need to look up the bash man page in your system if it supports. Also check typeset.
Other option is to use the ascii/decimal value of the choice character as the index of a normal array.
Sorry I dont have a solaris box at my disposal.
--ahamed
---------- Post updated at 11:52 PM ---------- Previous update was at 11:40 PM ----------
Something like this...
choice[$(printf "%d" "'P'")]=fun_P
choice[$(printf "%d" "'p'")]=fun_P
read key_press
eval ${choice[$(printf "%d" "'$key_press'")]}
As for default case, may be you should do a validation?
Smells like some sort of homework!
--ahamed
thanks again ahamed.
I could manage to make it work to some extent.....
Except how do I handle default case in here.
It can be used with *) in case - esac
I mean executing a function in case the input from user is anything else than what is assigned in array
---------- Post updated at 04:17 AM ---------- Previous update was at 04:01 AM ----------
Its done........
thanks ahamed for your help.......