enum data type seems not available in bash
bash, enums, linux
Solution
Try the following fragment of code ... I guess that it is what you want
#!/bin/bash
set -u
DEBUG=1
# This funcion allow to declare enum "types", I guess
enum ()
{
# skip index ???
shift
AA=${@##*\{} # get string strip after {
AA=${AA%\}*} # get string strip before }
AA=${AA//,/} # delete commaa
((DEBUG)) && echo $AA
local I=0
for A in $AA ; do
eval "$A=$I"
((I++))
done
}
### Main program
# Just declare enum as you need
enum index { OK_INDEX, CANCEL_INDEX, ERROR_INDEX, CONFIRM_INDEX, SAVE_INDEX, EXIT_INDEX };
# Print value of enumerated items
echo $OK_INDEX
echo $CANCEL_INDEX
echo $ERROR_INDEX
echo $CONFIRM_INDEX
echo $SAVE_INDEX
echo $EXIT_INDEX
# Use enumerated index in program
I=CONFIRM_INDEX
case $I in
OK_INDEX )
echo "Process here when index is $I"
;;
CANCEL_INDEX )
echo "Process here when index is $I"
;;
ERROR_INDEX )
echo "Process here when index is $I"
;;
CONFIRM_INDEX )
echo "Process here when index is $I"
;;
SAVE_INDEX )
echo "Process here when index is $I"
;;
EXIT_INDEX )
echo "Process here when index is $I"
;;
esac
exit 0
Problem
Having bash, created simple scripts for accessing array element by it's index.It as follows ``` #! /bin/bash OK_INDEX=0 CANCEL_INDEX=1 ERROR_INDEX=2 CONFIRM_INDEX=3 SAVE_INDEX=4 EXIT_INDEX=5 declare -a messageList=("ok" "cancel" "error" "confirm" "save" "exit") printf "%s \n" ${messageList[$CANCEL_INDEX]} ``` from above scripts i need to declare proper index variable to retrieve valid message from array list but it likely not handy for me to declare each variable and give index to them.It is nice if variable autometically getting value as like in C for `ENUM` data type in C it's possible by like ``` enum index { OK_INDEX, CANCEL_INDEX, ERROR_INDEX,CONFIRM_INDEX,SAVE_INDEX,EXIT_INDEX}; ``` is there any alternative for `ENUM` in bash? I found lot but not succeded then have try some trick to achieve this it is as follows ``` ENUM=(OK_INDEX CANCEL_INDEX ERROR_INDEX CONFIRM_INDEX SAVE_INDEX EXIT_INDEX) maxArg=${#ENUM[@]} for ((i=0; i < $maxArg; i++)); do name=${ENUM[i]} declare -r ${name}=$i done ``` So form above code snippet i successfully created constant but it seems lengthy means just declaring variable i need to write 5-10 lines code which is not fair. So any one have another solution?