Shell parse argument examples in Linux
Parsing arguments using manual loop
#!/bin/bash show_help(){ echo "Usage: ${0##*/} [-h|--help] [-v|--verbose] [-l|--lines number] FILE... " } while (( "$#" )); do case $1 in -h|--help) show_help exit ;; -l|--lines) if [ "$2" ] && [ ${2:0:1} != "-" ]; then number=$2 shift else echo "Option -l|--lines needs an argument" show_help exit 1 fi ;; -v|--verbose) verbose=1 ;; -?*) echo "Option $1 is not supported." show_help exit 1 ;; *) break esac shift done
Line 7 can be replace by “while :; do”
Parsing arguments using getopts
#!/bin/bash show_help(){ echo "Usage: ${0##*/} [-h] [-v] [-l number] FILE... " } #Consider set OPTIND in case it's used somewhere #OPTIND=1 while getopts hvl: opt; do case $opt in h) show_help exit 0 ;; v) verbose=1 ;; l) number=$OPTARG ;; ?) show_help >&2 exit 1 ;; esac done #Discard options already been parsed shift "$((OPTIND-1))"
1.getopts doesn’t support double dash like “–help”
2.getopts supports options combination like “-cvf”
3.In line 8, colon “:” means that option requires an argument