Monday, June 22, 2015

Enums in Bash

I find that I use a lot of bash scripts. Using cygwin on Windows, Mac and Linux they are cross platform (for the most part). One feature lacking in bash is enums, but you can simulate them. I ran across this StackOverflow post and there is a nice comment about enums in bash, but it isn't complete.

#!/bin/bash

STATES=(INITIAL DEFAULT_CS_SETUP CREATED_CS CHECKED_OUT_DIR MKELEMENT_FILE CREATED_BRANCH CHECKED_IN_DIR COMPLETE)
tam=${#STATES[@]}
for ((i=0; i < $tam; i++)); do
    name=${STATES[i]}
    declare -r ${name}=$i
done

echo get the INITIAL state
echo ${STATES[$INITIAL]}

echo get the next state from CREATED_CS
echo ${STATES[$CREATED_CS+1]}

echo list elements from CREATED_CS to the end
for ((i=$CREATED_CS; i < $tam; i++)); do
    echo ${STATES[$i]}
done

echo list elements from CREATED_CS to CREATED_BRANCH
for ((i=$CREATED_CS; i <= $CREATED_BRANCH; i++)); do
    echo ${STATES[$i]}
done

Often times I want to create an empty enum and add items to it. So here is my example of creating an enum type, OPTION_STATES, defining the enum values and adding an item to it and checking for it later.

#!/bin/bash

# Define enum type.
OPTION_STATES=(OPTION_ONE OPTION_TWO OPTION_THREE)

count=${#OPTION_STATES[@]}
for ((i=0; $i < $count; i++)); do
    name=${OPTION_STATES[$i]}
    declare -r ${name}=$i
    
    if [[ $DEBUG == true ]]; then
      echo $name $i
    fi
done

# Create instance of enum type, yes this is a hash table.
OPTIONS=()

# Put an element into the instance.
OPTIONS[$OPTION_ONE]=$OPTION_ONE

# Check if that element is in the instance.
if [[ ${OPTIONS[$OPTION_ONE]} == $OPTION_ONE ]]; then
  echo "woo hoo"
fi

No comments:

Post a Comment