Docu review done: Wed 31 Jul 2024 02:15:32 PM CEST

getopt

General

This script show the usage of getopt to handle arguments

und=$(tput sgr 0 1)             # Underline
bld=$(tput bold)                # Bold
err=${txtbld}$(tput setaf 1)    # red
ok=${txtbld}$(tput setaf 2)     # green
info=${txtbld}$(tput setaf 4)   # blue
bldwht=${txtbld}$(tput setaf 7) # white
rst=$(tput sgr0)                # Reset

usage() {
cat << EOF
Usage: $0 OPTIONS srcFile dstFile

OPTIONS:

--help      | -h    Display this message
--first     | -f    First argument, need a value
--second    | -s    Second argument, does not need a value (OPTIONAL)

${info}Example: $0 --first potatoe --second${rst}

EOF

exit 1
}

initII() {
    TEMP=$(getopt -s bash -o h,f:,s --longoptions help,first:,second -n 'template.sh' -- "$@")
    eval set -- "$TEMP"
    while true
    do
        case "${1}" in
            -f | --first)
                shift
                PROJECT="${1}"
                shift
                ;;
            -s | --second)
                shift
                ;;
            -h | --help)
                usage
                ;;
            --)
                shift
                break
                ;;
            *)
                echo "Incorrect parameter: $1"
                usage
                ;;
        esac
    done
}

init() {
    TEMP=`getopt -o h,f:,s --longoptions help,first:,second -n 'template.sh' -- "$@"`
    eval set -- "$TEMP"

    while true
    do
            case "$1" in
            -h | --help     )       usage;;
            -f | --first    )       FIRST="$2"; shift 2;;
            -s | --second   )       SECOND="1"; shift ;;
            --              )       shift; break;;
            *               )       echo "Incorrect parameter: $1"; usage;;
            esac
    done

    if [[ -z $FIRST ]]
    then
        echo "${err}The argument first is requierd${rst}"
        usage
    fi
}

action() {
    if [ "$SECOND" == "1" ]
    then
        options="second is set"
    else
        options="second is not set"
    fi

    echo "Performing action on ${info}${FIRST}${rst} ($options) ..."

    if [ $? == 0 ]
    then
        echo "${ok}Success.${rst}"
    else
        echo "${err}Fail.${rst}"
    fi
}

init $@
action