Bash arrays and case statements - review my script

Posted by Felipe Alvarez on Programmers See other posts from Programmers or by Felipe Alvarez
Published on 2012-06-13T04:27:12Z Indexed on 2012/06/13 4:47 UTC
Read the original article Hit count: 452

Filed under:
#!/bin/bash
# Change the environment in which you are currently working.
# Actually, it calls the relevant 'lettus.sh' script

if [ "${BASH_SOURCE[0]}" == "$0" ]; then
    echo "Try running this as \". chenv $1\""
    exit 0
fi

usage(){
    echo "Usage: . ${PROG}        -- Shows a list of user-selectable environments."
    echo "       . ${PROG} [env]  -- Select environment."
    echo "       . ${PROG} -h     -- Shows this usage screen."
    return
}

showEnv(){
    # check if index0 exists, assume we have at least the first (zeroth) element
    #if [ -z "${envList}" ]; then
    if [ -z "${envList[0]}" ]; then
        echo "array \$envList is empty! " >&2
        return 1
    fi

    # Show all elements in array (0 -> n-1)
    for i in $(seq 0 $((${#envList[@]} - 1))); do
        echo ${envList[$i]}
    done
    return
}
setEnv(){
    if [ -z "$1" ]; then
        usage; return
    fi

    case $1 in
        cold)       FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_cold.sh;;
        coles)      FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_coles.sh;;
        fc)         FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fc.sh;;
        fcrm)       FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fcrm.sh;;
        stable)     FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_stable.sh;;
        tip)        FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_tip.sh;;
        uat)        FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_uat.sh;;
        wellmdc)    FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_wellmdc.sh;;
        *)          usage; return;;
    esac

    if $IS_SOURCED; then
        echo "Environment \"$1\" selected."
        echo "Now sourcing file \"$FILE_TO_SOURCE\"..."
        . ${FILE_TO_SOURCE}
        return
    else
        return 1
    fi
}

main(){
    if [ -z "$1" ]; then
        showEnv; return
    fi

    case $1 in
        -h) usage;;
         *) setEnv $1;;
    esac
    return
}

PROG="chenv"

# create array of user-selectable environments
envList=( cold coles fc fcrm stable tip uat wellmdc )

main "$@"
return

If I could, I'd like to get some feedback on a better way to accomplish any of the following:

  1. run through the case statement
  2. make script trivally simple to maintain/upgrade/update

© Programmers or respective owner

Related posts about bash