Programming Tips - bash: Have a bash script accept options with a dash (-)

Date: 2010feb21 Update: 2025jun27 Language: bash OS: Linux Q. bash: Have a bash script accept options with a dash (-) A. Use the builtin getopts (not the external getopt). Here is an example:
#!/bin/bash # Usage: <my-script> [-v][-l <level>] VERBOSE=no LEVEL=5 while getopts "vl:" FLAG; do # At this point 3 variables are set echo --- echo FLAG=$FLAG echo OPTIND=$OPTIND echo OPTARG=$OPTARG echo case $FLAG in v ) VERBOSE=yes ;; l ) LEVEL=$OPTARG ;; esac done echo VERBOSE=$VERBOSE echo LEVEL=$LEVEL if [[ $VERBOSE == yes ]]; then echo 'Verbose is selected' fi
See `help getopts` for more info