si9ma
5/4/2019 - 2:06 AM

parse shell function arguments

parse shell function arguments

fun() {
    # usage
    read -r -d '' usage << EOM
usage: $0 [-h] [-u=<user>] [-e] [-p=<port>] host
    -h help
    -u user name
    -p ssh port
    -e if remote editable?
EOM

    # variable
    local host= user=root port=22 edit=

    # parse arguments
    while [ "$1" != "" ]; do
        PARAM=`cut -d '=' -f 1 <<< "$1"`
        VALUE=`cut -d '=' -f 2- <<< "$1"`
        case $PARAM in
            -h)
                echo $usage
                return
                ;;
            -u)
                user="$VALUE"
                ;;
            -p)
                port="$VALUE"
                ;;
            -e)
                edit="true"
                ;;
            *)
                echo "ERROR: unknown parameter \"$PARAM\""
                echo $usage && return
                ;;
        esac
        shift
    done

    # logic
    [ "$host" = "" ] && echo "[ERROR] Please provide host" && echo $usage && return
    ssh -p $post $user@$host
}