Handling Optional Arguments

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 129 of 205

An optional argument is one the user may leave out. The script must behave sensibly both when it is given and when it is not. That sounds simple, but "optional" covers several different shapes: an extra operand at the end of the command line, a flag that switches a behavior on, a flag that can be repeated to increase an effect, an option that may or may not carry a value, and an option that can appear many times to build a list. Each shape needs its own handling, and in each case the script needs a reliable way to tell "not given" apart from "given with an empty value".

This lesson covers each shape in turn and then combines them in one script. Lesson 132 focuses on choosing and applying default values once you know an argument was not given.

Optional Operands

The simplest optional argument is an operand that may or may not be present. A script that greets someone with an optional custom greeting can test the argument count:

name=$1
if (( $# >= 2 )); then
    greeting=$2
    echo "greeting given: [$greeting]"
else
    echo "no greeting given"
fi

$# >= 2 asks whether a second argument exists at all, regardless of its content. Two other common tests answer different questions, and the difference shows when the second argument is an empty string:

[[ ${2+set} == set ]] && echo "\${2+set} says: given" || echo "\${2+set} says: not given"
[[ -n ${2-} ]] && echo "-n says: non-empty" || echo "-n says: empty or missing"

Run three ways, with all three tests in one script:

$ bash opt1.sh ana
no greeting given
${2+set} says: not given
-n says: empty or missing
$ bash opt1.sh ana hi
greeting given: [hi]
${2+set} says: given
-n says: non-empty
$ bash opt1.sh ana ''
greeting given: []
${2+set} says: given
-n says: empty or missing
  • (( $# >= 2 )) and ${2+set} are true whenever the argument exists, even if it is empty. ${2+set} expands to set when $2 is set and to nothing otherwise (lesson 45).
  • [[ -n ${2-} ]] is true only when the argument exists and is non-empty. The - in ${2-} keeps the test safe under set -u (lesson 120).

Which one is right depends on whether an empty value means something. For a greeting, an empty string probably should be treated like a missing one; for a prefix or a separator, an empty string can be a deliberate choice.

A Variable Number of Trailing Operands

When any number of extra operands may follow the required ones, shift away the required ones and keep the rest as an array:

target=$1
shift
extras=("$@")
echo "target=[$target] extras=${#extras[@]}"
for e in "${extras[@]}"; do echo "  extra [$e]"; done
$ bash rest.sh srv1
target=[srv1] extras=0
$ bash rest.sh srv1 "a b" c
target=[srv1] extras=2
  extra [a b]
  extra [c]

With no extras, the array is empty and the loop body never runs. Copying "$@" into an array (lesson 104) keeps each argument intact, including the one with a space.

Boolean Flags

A flag is an option without a value: it is either present or absent. The usual implementation starts a variable at 0 and sets it to 1 when the flag appears:

ignore_case=0
...
-i) ignore_case=1 ;;
...
(( ignore_case )) && cmd+=(-i)

Using 0 and 1 lets the script test the flag with (( ignore_case )), which reads naturally and avoids string comparisons. Giving the flag twice simply sets the variable to 1 twice.

Counting Flags

Some flags mean "more" each time they appear. -v for verbosity is the classic example: -v shows some detail, -vv more, -vvv everything. Instead of setting the variable to 1, the parser adds 1:

verbose=0
while (( $# > 0 )); do
    case $1 in
        -v|--verbose) verbose=$((verbose + 1)) ;;
        -q|--quiet)   verbose=0 ;;
        -v*)          set -- "-v" "-${1:2}" "${@:2}"; continue ;;
        *) break ;;
    esac
    shift
done
echo "verbose level: $verbose"
(( verbose >= 1 )) && echo "info: level 1 message"
(( verbose >= 2 )) && echo "debug: level 2 message"
(( verbose >= 3 )) && echo "trace: level 3 message"
exit 0

The -v* pattern splits bundles such as -vvv into separate -v arguments, using the technique from lesson 127. The script ends with exit 0 because its last && line would otherwise leave status 1 whenever the level is low.

$ bash verb.sh
verbose level: 0
$ bash verb.sh -v -v
verbose level: 2
info: level 1 message
debug: level 2 message
$ bash verb.sh -vvv
verbose level: 3
info: level 1 message
debug: level 2 message
trace: level 3 message
$ bash verb.sh --verbose -vv
verbose level: 3
...
$ bash verb.sh -vv -q
verbose level: 0
$ bash verb.sh -q -v
verbose level: 1
info: level 1 message

The last two runs show that the arguments are processed in order: -q resets the level, and any -v after it starts counting again.

Flags That Can Be Switched Off: "Last One Wins"

When a behavior can be switched on or off, scripts often provide both forms, such as --color and --no-color. Processing the arguments in order and letting each one overwrite the variable gives the "last one wins" rule that most tools follow. This is useful in practice: a wrapper script or an alias can set a default (--color), and the user can still override it by adding --no-color at the end of the command line.

Options with an Optional Value

GNU tools have a few options whose value is itself optional. ls describes one in its help text as --color[=WHEN]: the square brackets mean the =WHEN part may be left out. --color alone means "always", while --color=never or --color=auto choose explicitly.

The value of such an option can only be given with =. If --color never were allowed, the parser could not know whether never is the option's value or a file named never. A script implements this with two patterns, one for the bare option and one for the = form:

color=auto
while (( $# > 0 )); do
    case $1 in
        --color)          color=always ;;
        --color=*)        color=${1#*=} ;;
        --no-color)       color=never ;;
        *) echo "unknown: $1" >&2; exit 2 ;;
    esac
    shift
done
case $color in
    always|never|auto) ;;
    *) echo "invalid --color value '$color' (use always, never or auto)" >&2; exit 2 ;;
esac
if [[ $color == auto ]]; then
    [[ -t 1 ]] && use=yes || use=no
else
    [[ $color == always ]] && use=yes || use=no
fi
echo "color=$color use_color=$use"
$ bash color.sh
color=auto use_color=no
$ bash color.sh --color
color=always use_color=yes
$ bash color.sh --color=never
color=never use_color=no
$ bash color.sh --color --no-color
color=never use_color=no
$ bash color.sh --no-color --color=always
color=always use_color=yes
$ bash color.sh --color=sometimes
invalid --color value 'sometimes' (use always, never or auto)
$ bash color.sh --color never
unknown: never

There are three distinct states here: the option was not given (auto, decided by the environment), given without a value (always), or given with a value. auto uses [[ -t 1 ]] to check whether standard output is a terminal (lesson 72). The runs above were captured through a pipe, so auto turned color off; run in a real terminal, the same command printed color=auto use_color=yes.

The last run shows the ambiguity rule in action: never was not taken as a value, and because this small script accepts no operands, it was rejected.

Short options should not have optional values. With -c taking an optional value, -c 3 would be ambiguous in the same way, and getopts (lesson 130) does not support optional values at all.

Repeatable Options That Build a List

Some options can be given several times, with each occurrence adding a value: grep -e PATTERN -e PATTERN or --exclude=GLOB --exclude=GLOB. An array collects them:

patterns=()
excludes=()
while (( $# > 0 )); do
    case $1 in
        -e) patterns+=("$2"); shift ;;
        --exclude=*) excludes+=("${1#*=}") ;;
        *) break ;;
    esac
    shift
done
echo "patterns: ${#patterns[@]}"; printf '  [%s]\n' "${patterns[@]}"
echo "excludes: ${#excludes[@]}"; printf '  [%s]\n' "${excludes[@]}"
$ bash rep.sh -e error -e "time out" --exclude='*.gz' --exclude=old.log
patterns: 2
  [error]
  [time out]
excludes: 2
  [*.gz]
  [old.log]

The array keeps the values separate and in order, including the one with a space and the glob pattern, which must not be expanded at this stage. The user quoted '*.gz' so that the shell passed it unexpanded, and the script's quoted "${1#*=}" keeps it that way. (This short demo omits the missing-value check for -e; the complete example below includes it.)

"Last one wins" and "every one counts" are both valid designs for a repeated option. Choose one deliberately for each option and say which in the help text.

Recording Whether an Option Was Given

Often the variable's own value can show whether an option was given: an empty context means -c was not used, a 0 in verbose means no -v. This breaks down when the empty or zero value is itself a valid choice. A --prefix option that accepts an empty prefix, for example, cannot use an empty variable to mean "not given". In that case keep a separate marker:

prefix= prefix_given=0
...
--prefix=*) prefix=${1#*=}; prefix_given=1 ;;
...
if (( prefix_given )); then
    echo "using prefix [$prefix]"
fi

Lesson 132 shows how to apply defaults only when such a marker says the user did not choose a value.

A Complete Example

search.sh is a small wrapper around grep that combines every shape from this lesson: a required but repeatable option (-e), a flag (-i), an option with a validated value that is used only when given (-c), a counter (-v), an option with an optional value plus a negative form (--color, --no-color), and optional operands (files, with standard input as the fallback).

#!/usr/bin/env bash
# search.sh [OPTIONS] -e PATTERN [-e PATTERN]... [FILE...]
set -euo pipefail
prog=${0##*/}

usage() {
    cat <<USAGE
usage: $prog [OPTIONS] -e PATTERN [-e PATTERN]... [FILE...]
  -e PATTERN        pattern to search for (repeatable, at least one)
  -i                ignore case
  -c N              show N lines of context (default: none)
  -v                more detail on stderr (repeatable: -vv)
  --color[=WHEN]    color matches: always (the default for --color), never, auto
  --no-color        same as --color=never
With no FILE, read standard input.
USAGE
}
bad_usage() {
    printf '%s: %s\n' "$prog" "$*" >&2
    printf "Try '%s --help' for more information.\n" "$prog" >&2
    exit 2
}
need_value() { (( $2 >= 2 )) || bad_usage "option '$1' requires an argument"; }

patterns=()      # repeatable option: every -e adds one
ignore_case=0    # flag: present or absent
context=         # optional value: empty means "not given"
verbose=0        # counter
color=auto       # optional value with a default; last one wins
files=()         # optional operands

while (( $# > 0 )); do
    case $1 in
        -h|--help)   usage; exit 0 ;;
        -e)          need_value "$1" "$#"; patterns+=("$2"); shift ;;
        -e?*)        patterns+=("${1#-e}") ;;
        -i)          ignore_case=1 ;;
        -c)          need_value "$1" "$#"; context=$2; shift ;;
        -c?*)        context=${1#-c} ;;
        -v)          verbose=$((verbose + 1)) ;;
        --color)     color=always ;;
        --color=*)   color=${1#*=} ;;
        --no-color)  color=never ;;
        --)          shift; files+=("$@"); break ;;
        -[!-]?*)     set -- "${1:0:2}" "-${1:2}" "${@:2}"; continue ;;
        -?*)         bad_usage "unrecognized option '$1'" ;;
        *)           files+=("$1") ;;
    esac
    shift
done

(( ${#patterns[@]} > 0 )) || bad_usage "at least one -e PATTERN is required"
case $color in always|never|auto) ;; *) bad_usage "invalid --color value '$color'" ;; esac
if [[ -n $context && ! $context =~ ^[0-9]{1,3}$ ]]; then
    bad_usage "context must be a number from 0 to 999, got '$context'"
fi

# Build the grep command from what was (and was not) given
cmd=(grep -H -n --color="$color")
(( ignore_case )) && cmd+=(-i)
[[ -n $context ]] && cmd+=(-C "$((10#$context))")
for p in "${patterns[@]}"; do cmd+=(-e "$p"); done
cmd+=(--)
if (( ${#files[@]} > 0 )); then cmd+=("${files[@]}"); else cmd+=(-); fi

(( verbose >= 1 )) && printf '%s: %d pattern(s), %d file(s)\n' "$prog" "${#patterns[@]}" "${#files[@]}" >&2
(( verbose >= 2 )) && printf '%s: running:%s\n' "$prog" "$(printf ' %q' "${cmd[@]}")" >&2

"${cmd[@]}"

How the Optional Arguments Are Used

The key idea is that each optional argument changes the final command only when it was given. The script builds the grep command in an array (lesson 98), adding pieces conditionally:

  • -i is appended only when the flag was seen.
  • -C N is appended only when context is non-empty, so leaving out -c means "no context lines" rather than "context 0". 10# turns input such as 03 into 3.
  • One -e is appended per collected pattern, so patterns with spaces or leading dashes reach grep intact.
  • -- protects file names that start with a dash, and - is passed when no files were given, which makes grep read standard input.

Other details:

  • -e?* and -c?* accept attached values (-eerror, -c1) and come before the bundling pattern, as lesson 127 explained. -ie error is split into -i and -e, and -e then takes error from the next argument.
  • -?* matches only arguments of two or more characters starting with a dash, so a lone - falls through to * and is treated as a file name meaning standard input.
  • The verbose messages go to standard error. At level 2 the script prints the exact command it will run, quoted with printf %q so that the boundaries between arguments are visible.
  • The final command runs last, so the script's exit status is grep's: 0 when something matched, 1 when nothing matched, 2 on errors.

Running the Complete Example

The file app.log contains five lines (start, ERROR disk full, ok, warning: time out, end), and setup notes.txt contains Error in config and fine.

Without -i, the search is case-sensitive and finds nothing:

$ bash search.sh -e error app.log
$ echo $?
1

With the flag, and with a file name that contains a space:

$ bash search.sh -i -e error app.log "setup notes.txt"
app.log:2:ERROR disk full
setup notes.txt:1:Error in config

Two patterns, with -i and -e bundled:

$ bash search.sh -ie error -e "time out" app.log
app.log:2:ERROR disk full
app.log:4:warning: time out

Context lines appear only when -c is given; grep marks them with - instead of ::

$ bash search.sh -e "time out" -c 1 app.log
app.log-3-ok
app.log:4:warning: time out
app.log-5-end

The same result came from the attached form -c1 -e"time out", and -ic0 -eerror app.log printed only app.log:2:ERROR disk full.

Verbosity level 2 shows the command that was built:

$ bash search.sh -vv -i -e error -- app.log "setup notes.txt"
search.sh: 1 pattern(s), 2 file(s)
search.sh: running: grep -H -n --color=auto -i -e error -- app.log setup\ notes.txt
app.log:2:ERROR disk full
setup notes.txt:1:Error in config

With no files, the script reads standard input, and grep labels the matches accordingly:

$ printf 'one\ntwo error\n' | bash search.sh -e error
(standard input):2:two error

--color without a value forced color even though the output went to a pipe; viewing the bytes with od -c showed escape sequences such as 033 [ 3 5 m around the file name. Adding --no-color after it switched color off again, and the output was plain text.

Usage errors stop the script with status 2 before grep runs:

$ bash search.sh app.log
search.sh: at least one -e PATTERN is required
Try 'search.sh --help' for more information.
$ bash search.sh -c abc -e x app.log
search.sh: context must be a number from 0 to 999, got 'abc'
Try 'search.sh --help' for more information.
$ bash search.sh --color=sometimes -e x app.log
search.sh: invalid --color value 'sometimes'
Try 'search.sh --help' for more information.

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 Handling Optional Arguments and get answers drawn from it.

Signed-in readers only.