How to make a multi-character parameter in UNIX using getopt?

微笑、不失礼 提交于 2019-12-01 02:27:12

getopt doesn't support what you are looking for. You can either use single-letter (-a) or long options (--long). Something like -ab is treated the same way as -a b: as option a with argument b. Note that long options are prefixed by two dashes.

i was struggling with this for long - then i got into reading about getopt and getopts

single char options and long options .

I had similar requirement where i needed to have number of multichar input arguments.

so , i came up with this - it worked in my case - hope this helps you

function show_help {
    echo "usage:  $BASH_SOURCE --input1 <input1> --input2 <input2> --input3 <input3>"
    echo "                     --input1 - is input 1 ."
    echo "                     --input2 - is input 2 ."
    echo "                     --input3 - is input 3 ."
}

# Read command line options
ARGUMENT_LIST=(
    "input1"
    "input2"
    "input3"
)



# read arguments
opts=$(getopt \
    --longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
    --name "$(basename "$0")" \
    --options "" \
    -- "$@"
)


echo $opts

eval set --$opts

while true; do
    case "$1" in
    h)
        show_help
        exit 0
        ;;
    --input1)  
        shift
        empId=$1
        ;;
    --input2)  
        shift
        fromDate=$1
        ;;
    --input3)  
        shift
        toDate=$1
        ;;
      --)
        shift
        break
        ;;
    esac
    shift
done

Note - I have added help function as per my requirement, you can remove it if not needed

That's not the unix way, though some do it e.g. java -cp classpath.

Hack: instead of -ab arg, have -b arg and a dummy option -a.

That way, -ab arg does what you want. (-b arg will too; hopefully that's not a bug, but a shortcut feature...).

The only change is your line:

-ab) shift;echo "You typed ab $1.";shift;;

becomes

-b) shift;echo "You typed ab $1.";shift;;
ghostdog74

getopt supports long format. You can search SO for such examples. See here, for example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!