0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Parse Command Line Arguments Easily

Use getopts in Bash to parse command line arguments like options and flags; for example, while getopts ":a:b" opt; do case $opt in a) echo "Option a with value $OPTARG" ;; b) echo "Option b set" ;; esac; done.
📋

Examples

Input./script.sh -a hello -b
OutputOption a with value hello Option b set
Input./script.sh -b
OutputOption b set
Input./script.sh -a
OutputOption -a requires an argument.
🧠

How to Think About It

To parse command line arguments in Bash, think of options as flags that may or may not have values. Use getopts to loop through each option and handle its value if required. This helps your script understand what the user wants without manual string checks.
📐

Algorithm

1
Start reading the command line arguments one by one.
2
Check if the current argument is an option (starts with a dash).
3
If the option requires a value, read the next argument as its value.
4
Store or act on the option and its value accordingly.
5
Repeat until all options are processed.
💻

Code

bash
#!/bin/bash
while getopts ":a:b" opt; do
  case $opt in
    a) echo "Option a with value $OPTARG" ;; 
    b) echo "Option b set" ;;
    :) echo "Option -$OPTARG requires an argument."; exit 1 ;; 
    \?) echo "Invalid option: -$OPTARG"; exit 1 ;;
  esac
done
Output
Option a with value hello Option b set
🔍

Dry Run

Let's trace './script.sh -a hello -b' through the code

1

Start getopts loop

opt = 'a', OPTARG = 'hello'

2

Handle option a

Print 'Option a with value hello'

3

Next getopts iteration

opt = 'b', no OPTARG

4

Handle option b

Print 'Option b set'

IterationoptOPTARGAction
1ahelloPrint 'Option a with value hello'
2bPrint 'Option b set'
💡

Why This Works

Step 1: Using getopts

The getopts command reads options one by one from the command line arguments.

Step 2: Option handling

Inside the case statement, each option is matched and handled accordingly.

Step 3: Error handling

If an option requires an argument but none is given, getopts triggers the : case to show an error.

🔄

Alternative Approaches

Manual parsing with a while loop
bash
#!/bin/bash
while [[ $# -gt 0 ]]; do
  case "$1" in
    -a)
      echo "Option a with value $2"
      shift 2
      ;;
    -b)
      echo "Option b set"
      shift
      ;;
    *)
      echo "Unknown option $1"
      exit 1
      ;;
  esac
done
This method is simple but requires manual shifting and careful checks; less robust than getopts.
Using getopt command
bash
#!/bin/bash
ARGS=$(getopt -o a:b -- "$@")
eval set -- "$ARGS"
while true; do
  case "$1" in
    -a) echo "Option a with value $2"; shift 2;;
    -b) echo "Option b set"; shift;;
    --) shift; break;;
    *) echo "Invalid option"; exit 1;;
esac
done
getopt supports long options and more complex parsing but is less portable and more complex.

Complexity: O(n) time, O(1) space

Time Complexity

Parsing command line arguments with getopts is linear in the number of arguments, so O(n).

Space Complexity

The script uses constant extra space, O(1), as it processes arguments one by one without storing all.

Which Approach is Fastest?

getopts is efficient and built-in, manual parsing is simple but error-prone, getopt is powerful but less portable.

ApproachTimeSpaceBest For
getoptsO(n)O(1)Simple option parsing
Manual parsingO(n)O(1)Very simple scripts, custom logic
getopt commandO(n)O(1)Complex options, long options
💡
Use getopts for simple, reliable option parsing in Bash scripts.
⚠️
Beginners often forget to handle missing option arguments, causing unexpected script behavior.