Parsing Script Arguments

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 127 of 205

A script receives its command-line arguments as a plain list of strings in $1, $2 and so on (lesson 42). Bash does not know which of them are options, which are values for options and which are file names; it is the script's job to work that out. This process is called argument parsing. A script that parses its arguments well accepts the same forms users already know from tools like ls, grep and cp, reports mistakes clearly and treats unusual file names safely.

This lesson explains the conventions that command-line arguments follow and builds a parsing loop with while, case and shift that handles all of them. The lessons that follow go deeper into individual parts: validating required arguments (128), optional arguments (129), the getopts builtin (130), help messages (131), defaults (132) and invalid input (133).

What the Script Actually Receives

Before parsing anything, it helps to look at the raw list. This small script prints the number of arguments and each argument in brackets:

printf 'argc=%d\n' "$#"
i=0
for a in "$@"; do i=$((i+1)); printf '%d: [%s]\n' "$i" "$a"; done
bash show.sh -v --output=report.txt -n 5 "my file.txt" -- -odd
argc=7
1: [-v]
2: [--output=report.txt]
3: [-n]
4: [5]
5: [my file.txt]
6: [--]
7: [-odd]

By the time the script runs, the shell has already removed the quotes, so "my file.txt" arrives as one argument containing a space. Everything else, such as whether 5 belongs to -n or whether -- means anything, is left to the script.

The Conventions Users Expect

Most Unix-like command-line tools follow the same rules, partly from the POSIX utility guidelines and partly from GNU conventions:

  • Short options are a dash and one letter: -v, -l.
  • Long options are two dashes and a word: --verbose, --lines.
  • Option arguments are values that belong to an option. A short option takes its value as the next argument (-o out.txt) or attached to it (-oout.txt). A long option takes it as the next argument (--output out.txt) or after an equals sign (--output=out.txt).
  • Bundled short options: several short options without values can be combined, so -lw means -l -w.
  • Operands are the arguments that are not options, usually file names or other objects the command acts on.
  • -- ends the options. Everything after it is an operand, even if it starts with a dash. This is how a user passes a file named -data.txt.
  • A single - is an operand, and by convention means standard input (or standard output, depending on the position).

GNU tools also accept options after operands (ls a.txt -l), while strict POSIX parsing stops at the first operand. The loop in this lesson follows the GNU style; lesson 130 shows the POSIX style with getopts.

Simple Case: Arguments by Position

When a script takes a fixed number of operands and no options, there is nothing to parse; each argument has a meaning given by its position:

src=$1
dest=$2
echo "copy from [$src] to [$dest]"
copy from [notes.txt] to [backup/]
copy from [notes.txt] to []

The second run was missing the destination, and the script silently used an empty string. Positional scripts are simple, but they must check the number of arguments, which lesson 128 covers in detail.

Why a for Loop Is Not Enough

A for arg in "$@" loop visits each argument once, which works for options without values. It cannot handle an option followed by its value, because the loop has no way to consume the next argument:

for arg in "$@"; do
    case $arg in
        -v) echo "verbose" ;;
        -o) echo "output... but which value?" ;;
        *)  echo "operand: $arg" ;;
    esac
done
verbose
output... but which value?
operand: out.txt
operand: a.txt

out.txt was meant to be the value of -o, but the loop treated it as a file to process. Parsing needs a loop that can look at the current argument and take the one after it.

The while, case and shift Loop

The standard solution is a while loop that always inspects $1, decides what it is, and removes it with shift (lesson 44). When an option needs a value, the loop reads $2 and shifts once more:

#!/usr/bin/env bash
prog=${0##*/}
verbose=0
dry_run=0
output=
files=()
while (( $# > 0 )); do
    case $1 in
        -v|--verbose)  verbose=1 ;;
        -n|--dry-run)  dry_run=1 ;;
        -o|--output)
            if (( $# < 2 )); then
                printf '%s: option %s needs a value\n' "$prog" "$1" >&2; exit 2
            fi
            output=$2
            shift ;;
        --output=*)    output=${1#*=} ;;
        --)            shift; files+=("$@"); break ;;
        -*)            printf '%s: unknown option: %s\n' "$prog" "$1" >&2; exit 2 ;;
        *)             files+=("$1") ;;
    esac
    shift
done
printf 'verbose=%s dry_run=%s output=[%s]\n' "$verbose" "$dry_run" "$output"
printf 'files (%d):' "${#files[@]}"
printf ' [%s]' "${files[@]}"
echo

How the Loop Works

  • while (( $# > 0 )) runs as long as arguments remain. Each pass handles the argument currently in $1.
  • The final shift after esac removes the argument that was just handled, so the next pass sees the following one.
  • Flags such as -v only set a variable.
  • Options with a value first check that a value exists ($# < 2 means $1 is the last argument), copy $2, and shift an extra time so the value is not processed again as an operand.
  • --output=* matches the equals form. ${1#*=} removes everything up to and including the first =, so --output=dir/a=b.txt correctly gives dir/a=b.txt.
  • -- shifts itself away, appends all remaining arguments to the operand list exactly as they are, and leaves the loop with break.
  • -* catches every other argument that starts with a dash. Because case tries patterns from top to bottom (lesson 75), known options are matched first and only unknown ones reach this line.
  • * collects operands into the files array (lesson 99), which keeps names with spaces intact.

Running It

Options before, between and after operands all work:

$ bash parse.sh -v a.txt
verbose=1 dry_run=0 output=[]
files (1): [a.txt]

$ bash parse.sh a.txt --verbose b.txt
verbose=1 dry_run=0 output=[]
files (2): [a.txt] [b.txt]

The three forms of the output option give the same result:

$ bash parse.sh -o out.txt a.txt
verbose=0 dry_run=0 output=[out.txt]
files (1): [a.txt]

bash parse.sh --output out.txt a.txt and bash parse.sh --output=out.txt a.txt print the same two lines.

Mistakes are reported with status 2, the usual code for incorrect usage (lesson 116):

$ bash parse.sh -o
parse.sh: option -o needs a value
$ bash parse.sh -x a.txt
parse.sh: unknown option: -x

After --, an argument that looks like an option is treated as a file name:

$ bash parse.sh -- -v a.txt
verbose=0 dry_run=0 output=[]
files (2): [-v] [a.txt]

Values containing spaces survive, as long as the user quotes them and the script quotes its variables:

$ bash parse.sh -o "my report.txt" "a b.txt" c.txt
verbose=0 dry_run=0 output=[my report.txt]
files (2): [a b.txt] [c.txt]

What This First Version Does Not Handle

Testing reveals three gaps:

$ bash parse.sh -vn a.txt
parse.sh: unknown option: -vn
$ bash parse.sh -
parse.sh: unknown option: -
$ bash parse.sh -o -v a.txt
verbose=0 dry_run=0 output=[-v]
files (1): [a.txt]

Bundled options are rejected, a lone - is mistaken for an option, and an option value that starts with a dash is accepted as the value. The last one is normal behavior: many standard tools also take the next argument as the value without checking it, which is the only way to pass a value that really does start with a dash. The first two are fixed in the complete example below. With no operands at all, printf ' [%s]' still prints [] once, because printf runs its format once even with no arguments; the complete example avoids this by giving the file list a default.

Splitting Bundled Short Options

Bundled options like -lw can be supported by rewriting the argument list: replace -lw with -l followed by -w, then let the loop process the result. The expansions ${1:0:2} (the first two characters) and ${1:2} (everything after them) do the splitting, and set -- replaces the positional parameters:

set -- -lw a.txt
echo "before: $*"
set -- "${1:0:2}" "-${1:2}" "${@:2}"
echo "after:  $*"
before: -lw a.txt
after:  -l -w a.txt

"${@:2}" keeps all remaining arguments unchanged. Inside the parsing loop, the case for this rewrite must be followed by continue instead of falling through to shift, so the loop processes the new $1 (-l) on its next pass. A bundle of three letters is split one letter at a time over several passes. Options that take a value need care: -ofile means -o with the value file, not -o -f -i -l -e, so a pattern for the attached form (-o?*) must appear before the bundling pattern.

A Complete Example

wc2.sh counts lines and words, like a small version of wc. It supports short and long options, bundling, attached and separate option values, --, - for standard input, and an output file. It uses the usage conventions from lesson 125: errors in the arguments print a short message and a Try '... --help' line on standard error and exit with 2, while --help prints usage on standard output and exits with 0.

#!/usr/bin/env bash
# wc2.sh [-l] [-w] [-o FILE] [--] [FILE...]: count lines and/or words
set -euo pipefail
prog=${0##*/}

usage() { printf 'usage: %s [-l] [-w] [-o FILE] [--] [FILE...]\n' "$prog"; }
bad_usage() {
    printf '%s: %s\n' "$prog" "$*" >&2
    printf "Try '%s --help' for more information.\n" "$prog" >&2
    exit 2
}

lines=0 words=0 output=
files=()
while (( $# > 0 )); do
    case $1 in
        -h|--help)    usage; exit 0 ;;
        -l|--lines)   lines=1 ;;
        -w|--words)   words=1 ;;
        -o|--output)
            (( $# >= 2 )) || bad_usage "option '$1' requires an argument"
            output=$2
            shift ;;
        -o?*)         output=${1#-o} ;;
        --output=*)   output=${1#*=} ;;
        --)           shift; files+=("$@"); break ;;
        -)            files+=("-") ;;
        -[!-]?*)      # bundled short options: -lw becomes -l -w
                      set -- "${1:0:2}" "-${1:2}" "${@:2}"
                      continue ;;
        -*)           bad_usage "unrecognized option '$1'" ;;
        *)            files+=("$1") ;;
    esac
    shift
done

# no -l and no -w: count both
(( lines || words )) || { lines=1; words=1; }
(( ${#files[@]} > 0 )) || files=("-")

count() {    # count FILE   ("-" means standard input)
    local name=$1 counts l w
    if [[ $1 == - ]]; then
        name="(stdin)"
        counts=$(wc -lw)
    else
        counts=$(wc -lw < "$1") || return 1
    fi
    read -r l w <<< "$counts"
    local out=$name
    (( lines )) && out+=" lines=$l"
    (( words )) && out+=" words=$w"
    printf '%s\n' "$out"
}

status=0
if [[ -n $output ]]; then
    exec > "$output"
fi
for f in "${files[@]}"; do
    count "$f" || status=1
done
exit "$status"

How the Pieces Fit

  • The order of the case patterns matters. -o?* (an -o with something attached) comes before -[!-]?* (any other single-dash argument longer than two characters), so -oout.txt is read as a value while -lw is split. -) comes before -*, so a lone dash is an operand. -[!-]?* cannot match a long option, because its second character must not be a dash.
  • Parsing only collects information. The loop sets variables and fills an array; the real work starts after it. Keeping these phases apart makes the script easier to read and makes it possible to check combinations of options before doing anything (lesson 128).
  • Defaults are applied after parsing: with neither -l nor -w the script counts both, and with no files it reads standard input. Lesson 132 covers defaults in detail.
  • exec > "$output" redirects the standard output of the rest of the script into the file (lesson 115 showed exec with logs), so the counting code does not need to know where its output goes.
  • Each file is counted separately, and a failure on one file sets the final status to 1 without stopping the others.

Running the Complete Example

With a.txt holding two lines and three words, b c.txt holding one line of three words, and a file named -data.txt:

$ bash wc2.sh a.txt
a.txt lines=2 words=3
$ bash wc2.sh -l a.txt
a.txt lines=2
$ bash wc2.sh -wl a.txt
a.txt lines=2 words=3
$ bash wc2.sh -w "b c.txt" a.txt
b c.txt words=3
a.txt words=3
$ bash wc2.sh -- -data.txt
-data.txt lines=1 words=1

The output options, run one after another, created three files:

$ bash wc2.sh -lo out1.txt a.txt     # out1.txt: a.txt lines=2
$ bash wc2.sh -oout2.txt a.txt       # out2.txt: a.txt lines=2 words=3
$ bash wc2.sh --output=out3.txt -w a.txt   # out3.txt: a.txt words=3

In the first one, -lo was split into -l and -o, and -o then took out1.txt as its value.

Reading standard input, alone or with - among other files:

$ printf 'a b\nc\n' | bash wc2.sh -l
(stdin) lines=2
$ printf 'a b\nc\n' | bash wc2.sh a.txt -
a.txt lines=2 words=3
(stdin) lines=2 words=3

Usage errors and file errors are reported differently:

$ bash wc2.sh -lx a.txt
wc2.sh: unrecognized option '-x'
Try 'wc2.sh --help' for more information.
$ bash wc2.sh a.txt missing.txt
a.txt lines=2 words=3
wc2.sh: line 47: missing.txt: No such file or directory

The first ended with status 2 and processed nothing, because the command line itself was wrong. The second ended with status 1 after processing the file that existed; the error line is Bash's own message for the failed < redirection, which already names the file and the reason.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Parsing Script Arguments and get answers drawn from it.

Signed-in readers only.