0

How can I use the getopts without a parameter?

while getopts ":a:f:l:r:h:v:" arg; do
   printf $arg
   case $arg in
     a)
        add_param=${OPTARG}
        ;;
     f)
        file_param=${OPTARG}
        ;;
     l)
        list_param=${OPTARG}
        ;;
     r)
       remove_param=${OPTARG}
       ;;
     v)
       version_param="version"
       printf "hello world"
       ;;
     h | *)
       print_usage
       exit_script
   esac
done

I never get in the case -v if I run my script like this sh script.sh -v because this implementation expects a parameter.

Can you help me to fix that?

1

From help getopts (in bash):

getopts: getopts optstring name [arg]
    Parse option arguments.

    Getopts is used by shell procedures to parse positional parameters
    as options.

    OPTSTRING contains the option letters to be recognized; if a letter
    is followed by a colon, the option is expected to have an argument,
    which should be separated from it by white space.

I think it's valid also for sh. You should try ":a:f:l:r:hv" instead of ":a:f:l:r:h:v:".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.