Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65

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:

$> ./getopts.sh
$> ./getopts.sh -h
./getopts.sh demonstrates Bash getopts command usage
$> ./getopts.sh -i
./getopts.sh: illegal option -- i
$> ./getopts.sh -o
./getopts.sh: option requires an argument -- o
$> ./getopts.sh -o 42
Options: 42
$> ./getopts.sh -o 42 -d /tmp
Options: 42
Directory: /tmp
$> ./getopts.sh -v
./getopts.sh - 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!