How to get arguments with flags in Bash

后端 未结 11 2099
余生分开走
余生分开走 2020-12-22 15:56

I know that I can easily get positioned parameters like this in bash:

$0 or $1

I want to be able to use flag options like this to s

11条回答
  •  伪装坚强ぢ
    2020-12-22 16:26

    This example uses Bash's built-in getopts command and is from the Google Shell Style Guide:

    a_flag=''
    b_flag=''
    files=''
    verbose='false'
    
    print_usage() {
      printf "Usage: ..."
    }
    
    while getopts 'abf:v' flag; do
      case "${flag}" in
        a) a_flag='true' ;;
        b) b_flag='true' ;;
        f) files="${OPTARG}" ;;
        v) verbose='true' ;;
        *) print_usage
           exit 1 ;;
      esac
    done
    

    Note: If a character is followed by a colon (e.g. f:), that option is expected to have an argument.

    Example usage: ./script -v -a -b -f filename

    Using getopts has several advantages over the accepted answer:

    • the while condition is a lot more readable and shows what the accepted options are
    • cleaner code; no counting the number of parameters and shifting
    • you can join options (e.g. -a -b -c-abc)

    However, a big disadvantage is that it doesn't support long options, only single-character options.

提交回复
热议问题