简体   繁体   中英

How to pass in shell scripts mandatory and optional flags in command line using getopts?

I want to pass 3 parameters with getopts to my shell script. The script requires at least the first 2, the third parameter is optional. If it is not set, its default is used. So that the following would both work:

sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"

I tried to do it like the following, but it constantly ignores my entered parameters.

usage() {
 echo "Usage: Script -a <homedir> -b <threads> -c <string>"
  echo "options:"
                echo "-h      show brief help"

  1>&2; exit 1;
}

string="bla"

while getopts h?d:t:a: args; do
case $args in
    -h|\?)
        usage;
        exit;;
    -a ) homedir=d;;
    -b ) threads=${OPTARG};;
    -c ) string=${OPTARG}
        ((string=="bla" || string=="blubb")) || usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done

I'm new to this getopts, before I just added the parameters in a specific order, which I don't want to do here. I have read a lot questions in here, but unfortenatly didn't find it the way I need it.

I really would appriciate your help here. Thanks:)

You have several mistakes in your script. Most importantly, $args only contains the letter of the option, without the leading dash. Also the option string you gave to getopts ( h?d:t:a: ) doesn't fit to the options you actually handle ( h , ? , a , b , c ). Here is a corrected version of the loop:

while getopts "h?c:b:a:" args; do
case $args in
    h|\?)
        usage;
        exit;;
    a ) homedir=d;;
    b ) threads=${OPTARG};;
    c ) string=${OPTARG}
        echo "Entered string: $string"
        [[ $string=="bla" || $string=="blubb" ]] && usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM