Java Programming Tutorials

Java programming tutorials with many code examples!

Bash script parameters


How to process Bash script parameters? There are two ways – using while-case combo or with Bash getopts as we show in the following example.


Basically there are two ways to process Bash script parameters:

  1. Using Bash case statement inside while loop.
  2. Using Bash getopts built-in command.

In the post Bash case statement we’ve shown how to process the parameters with while-loop case-statement combo. In this post we’re going to show how to use getopts to do that.


function usage() {
    echo "$0 demonstrates Bash getopts command usage"
    exit 1

function version() {
    echo "$0 - version: 0.0.1"
    exit 1

while getopts "d:o:hv" opt; do
    case "$opt" in
        d) TARGET_DIR="$OPTARG";;
        o) OPTIONS="$OPTARG";;
        v) version;;
        h) usage;;

echo "Options: ${OPTIONS}"
echo "Directory: ${TARGET_DIR}"

getopts takes a string of chars, which will be script options. Options that require arguments are followed by “:” (colon). Else just option char is needed. Read option is put in given variable (here opt) and its argument (if any) lands in OPTARG variable. OPTIND is an index of currently processed option and has to be reset everytime getopts is called.

And here’s result of processing a couple of script parameters:

$> ./
$> ./ -h
./ demonstrates Bash getopts command usage
$> ./ -i
./ illegal option -- i
$> ./ -o
./ option requires an argument -- o
$> ./ -o 42
Options: 42
$> ./ -o 42 -d /tmp
Options: 42
Directory: /tmp
$> ./ -v
./ - version: 0.0.1

As you can see Bash getopts automatically handles missing option arguments or illegal options.

If short options are enough, then go ahead with Bash getopts, but when you need more sophisticated parsing, like long, multi-word options, then use while case combo.

Share with the World!