Handling Unknown Options and Invalid Input

Su Suriya Ravichandran Updated 06 Dec 2026
19 min read ·Lesson 133 of 205

Every script that accepts arguments will sooner or later receive ones it cannot use: an option it does not know, an option without its value, a word where a number was expected, two options that contradict each other, or input that contains invisible control characters. How a script reacts decides whether the user fixes the problem in five seconds or gives up. A good reaction stops before doing any work, says exactly what was wrong and where it came from, points to the help, and uses an exit status that other programs can test.

Lessons 127 to 130 already added an "unknown option" branch to each parsing loop, and lesson 128 covered the checks for required arguments and their values. This lesson looks at the whole error path: the kinds of bad input, the difference between usage errors and data errors, suggestions for mistyped options, abbreviations of long options, negative numbers that look like options, reporting several problems at once, displaying hostile input safely, and re-asking when the input comes from a person instead of the command line.

Kinds of Bad Input

It helps to name the cases, because each one needs a slightly different message:

ProblemExampleTypical message
Unknown option-x, --colourunknown option '-x'
Missing option value-p at the endoption '-p' requires an argument
Value for a flag--verbose=yesoption '--verbose' does not take a value
Invalid value-p 9, -f xinvalid precision '9' (expected 0-6)
Missing required option or operandno -fmissing required option '--from'
Conflicting choices-f c -t c--from and --to are both 'c'
Too many operandscopy.sh a b conly one SOURCE can be given
Bad data while workinga temperature below absolute zero-5 K is below absolute zero

All but the last row are usage errors: the command line itself is wrong, and nothing should be done. The last row is a data error: the command line was valid, but one input could not be processed.

Usage Errors Versus Data Errors

The two kinds of error are handled differently:

  • A usage error stops the script immediately, before it changes anything. It prints a short message and the Try '... --help' hint to standard error and exits with status 2, the common convention for wrong usage (lesson 116). Some programs use 64 (EX_USAGE from sysexits.h) instead; either works as long as the help text says which one the script uses.
  • A data error affects one item. The script reports it, usually skips that item, continues with the rest, and exits with status 1 at the end, so the caller knows that something failed. There is no point printing the --help hint here, because the command line was correct.

Keeping the two apart matters to scripts that call yours: status 2 means "fix the command", status 1 means "check the input data".

Stop Before Doing Any Work

A usage error discovered halfway through a job leaves the job half done. Lesson 130 showed a getopts script that had already acted on -v when it found the unknown -x that followed. The reliable structure is:

  1. The parsing loop only records what the user asked for.
  2. A validation block checks all values and their combinations.
  3. Only then does the real work begin.

The complete example at the end of this lesson follows these three steps.

Mistyped Long Options: Suggestions

When a user types --verbsoe instead of --verbose, a plain "unknown option" message makes them search the help. Many modern tools (Git, for example) suggest the closest known option instead. "Closest" is usually measured with the edit distance (Levenshtein distance): the smallest number of single-character insertions, deletions and substitutions that turn one word into the other.

# distance A B: Levenshtein edit distance (insertions, deletions, substitutions)
distance() {
    local a=$1 b=$2 i j cost best
    local -a prev cur
    for (( j = 0; j <= ${#b}; j++ )); do prev[j]=$j; done
    for (( i = 1; i <= ${#a}; i++ )); do
        cur=("$i")
        for (( j = 1; j <= ${#b}; j++ )); do
            cost=1
            [[ ${a:i-1:1} == "${b:j-1:1}" ]] && cost=0
            best=$(( prev[j] + 1 ))
            (( cur[j-1] + 1 < best )) && best=$(( cur[j-1] + 1 ))
            (( prev[j-1] + cost < best )) && best=$(( prev[j-1] + cost ))
            cur[j]=$best
        done
        prev=("${cur[@]}")
    done
    echo "${prev[${#b}]}"
}

The function compares the words one character at a time and keeps one row of a table: prev[j] is the distance between the first i - 1 characters of A and the first j characters of B. Each new cell takes the cheapest of three moves: delete a character (prev[j] + 1), insert one (cur[j-1] + 1), or substitute (prev[j-1] + cost, where cost is 0 when the characters already match). The last cell of the last row is the answer:

verbsoe -> verbose: 2
colour -> color: 1
kitten -> sitting: 3
fro -> from: 1
prec -> precision: 5

Swapping two letters (so for os) counts as two substitutions, so verbsoe is at distance 2. The last line shows why edit distance alone is not enough: prec is clearly meant as precision, but it is five letters short. That case is better handled by abbreviations.

A suggestion should be made only when the distance is small (the example uses 2 or less). Otherwise every typo produces a confusing guess. For --colour, no option of the example script is close, so no suggestion is printed.

Unique Abbreviations of Long Options

GNU tools accept any unambiguous prefix of a long option: --prec for --precision, --verb for --verbose. If the prefix matches more than one option, it is an error, and the message lists the candidates. The complete example turns the option name into its full form before the case statement:

long_opts=(from to precision verbose version help)

# expand_long NAME: print the full option name for NAME or a unique prefix of it
expand_long() {
    local name=$1 opt d best=99 guess= matches=()
    for opt in "${long_opts[@]}"; do
        [[ $opt == "$name" ]] && { echo "$opt"; return 0; }
        [[ $opt == "$name"* ]] && matches+=("$opt")
    done
    if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
    if (( ${#matches[@]} > 1 )); then
        fail_usage "option '--$name' is ambiguous; possibilities:$(printf " '--%s'" "${matches[@]}")"
    fi
    for opt in "${long_opts[@]}"; do
        d=$(distance "$name" "$opt")
        if (( d < best )); then best=$d guess=$opt; fi
    done
    if (( best <= 2 )); then
        fail_usage "unknown option '--$name'" "did you mean '--$guess'?"
    fi
    fail_usage "unknown option '--$name'"
}

The order of the checks matters:

  1. An exact match wins immediately, so an option name that happens to be a prefix of another (to would be a prefix of a hypothetical total) still works.
  2. Exactly one prefix match is accepted.
  3. Several prefix matches are an error that names them all.
  4. No match: the closest option by edit distance is suggested if it is close enough.
$ bash tempconv.sh -f c -t f --verb 20
20 C = 68.0 F
$ bash tempconv.sh -f c -t f --ver 20
tempconv.sh: option '--ver' is ambiguous; possibilities: '--verbose' '--version'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --verbsoe 20
tempconv.sh: unknown option '--verbsoe'
tempconv.sh: did you mean '--verbose'?
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --tp f 20
tempconv.sh: unknown option '--tp'
tempconv.sh: did you mean '--to'?
Try 'tempconv.sh --help' for more information.

Abbreviations have one cost: adding a new option later can make an abbreviation that used to work ambiguous. Before --version was added, --ver meant --verbose. Scripts called by other scripts should therefore use full option names.

The caller runs full=$(expand_long "$name") || exit. Because the function runs inside $( ), its exit 2 ends only that subshell (lesson 118); its messages still reach the terminal because they go to standard error, and || exit then ends the script with the same status, 2.

Negative Numbers That Look Like Options

A temperature converter must accept -40. A parsing loop that treats every word starting with - as an option rejects it as an unknown option. There are two solutions, and a good script supports both:

  • -- ends option parsing (lesson 127), so tempconv.sh -f c -t f -- -40 always works.
  • Recognize numbers before options. If the argument matches a negative-number pattern, it is stored as an operand:
if [[ $arg =~ ^-[0-9]+(\.[0-9]+)?$ ]]; then       # a negative number, not an option
    values+=("$arg"); shift; continue
fi
$ bash tempconv.sh -f c -t f 100 37 -40
212.0
98.6
-40.0
$ bash tempconv.sh -f c -t f -- -40
-40.0

This works because the script has no options whose letters are digits. A script with an option such as -1 cannot use this shortcut, and must rely on --.

Reporting Several Problems at Once

If a command line has three mistakes, a script that stops at the first one makes the user run it three times to find them all. Collecting the messages in an array and reporting them together is friendlier:

errors=()
[[ -n $from ]] || errors+=("missing required option '--from'")
[[ -n $to ]]   || errors+=("missing required option '--to'")
[[ $precision =~ ^[0-6]$ ]] || errors+=("invalid precision $(show "$precision") (expected 0-6)")
(( ${#errors[@]} == 0 )) || fail_usage "${errors[@]}"

fail_usage prints each message on its own line, each with the script name in front, and then a single hint:

fail_usage() {     # fail_usage MESSAGE...: one line per message, then the hint
    local msg
    for msg in "$@"; do printf '%s: %s\n' "$prog" "$msg" >&2; done
    printf "Try '%s --help' for more information.\n" "$prog" >&2
    exit 2
}
$ bash tempconv.sh -f x -t c -p 9 abc 1e3 12.
tempconv.sh: invalid --from unit 'x' (expected c, f or k)
tempconv.sh: invalid precision '9' (expected 0-6)
tempconv.sh: invalid VALUE 'abc' (expected a number such as 21 or -3.5)
tempconv.sh: invalid VALUE '1e3' (expected a number such as 21 or -3.5)
tempconv.sh: invalid VALUE '12.' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.

Writing the loop instead of printf '%s: %s\n' "$prog" "$@" is deliberate: printf reuses its format for the remaining arguments, so it would pair the second message with the third as if it were the program name. Lesson 128 ran into the same effect.

Collecting all errors works only for independent checks. Parsing errors (an unknown option, a missing value) still stop the loop at once, because after them the script can no longer tell which word is an option and which is a value.

Each message also says what was expected. "invalid precision '9'" leaves the user guessing; "(expected 0-6)" tells them how to fix it.

Showing Odd Input Safely

A message that prints the user's input exactly as given can mislead. An argument ending in a newline prints a blank line in the middle of the message; one containing terminal escape sequences can change the colors of the terminal or hide text. A small helper puts normal values in quotes and shows anything with control characters in the $'...' form produced by printf %q:

show() {           # quote a value for a message; make control characters visible
    if [[ $1 == *[![:print:]]* ]]; then printf '%q' "$1"; else printf "'%s'" "$1"; fi
}
$ bash tempconv.sh -f c -t f $'12\n'
tempconv.sh: invalid VALUE $'12\n' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f $'-\e[31m'
tempconv.sh: unknown option $'-\E[31m'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f "1 2"
tempconv.sh: invalid VALUE '1 2' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.

The second argument contains the escape sequence that turns text red. Printed raw, it would have colored the rest of the terminal; through show, it is visible as \E[31m and harmless. [[:print:]] matches printable characters, including the space, so '1 2' is shown in ordinary quotes.

Invalid Input from a Person: Ask Again

Command-line arguments are checked once, and the script exits on error. Input typed at a prompt is different: the person is still there, so the friendly reaction is to explain the problem and ask again, with a limit on the number of attempts. The script must also stop cleanly when input ends (Ctrl + D, or a pipe that runs out), instead of looping forever (lesson 87):

#!/usr/bin/env bash
# ask_number PROMPT MIN MAX: read a whole number in a range, with 3 attempts
ask_number() {
    local prompt=$1 min=$2 max=$3 reply tries
    for (( tries = 1; tries <= 3; tries++ )); do
        printf '%s [%d-%d]: ' "$prompt" "$min" "$max" >&2
        if ! IFS= read -r reply && [[ -z $reply ]]; then
            printf '\nno answer (end of input)\n' >&2
            return 1
        fi
        if [[ $reply =~ ^[0-9]+$ ]] && (( 10#$reply >= min && 10#$reply <= max )); then
            echo "$((10#$reply))"
            return 0
        fi
        printf '%q is not a number from %d to %d\n' "$reply" "$min" "$max" >&2
    done
    echo "too many invalid answers" >&2
    return 1
}
if n=$(ask_number "How many copies" 1 10); then
    echo "making $n copies"
else
    exit 1
fi

The prompt and the complaints go to standard error, and only the accepted number goes to standard output, so n=$(ask_number ...) captures just the number (lesson 91). 10# makes 07 mean 7 instead of an invalid octal number (lesson 128). The condition ! read && [[ -z $reply ]] accepts a final line without a newline but stops when there is really nothing left.

The runs below used piped input, so the typed answers do not appear after the prompts:

$ printf 'ten\n0\n07\n' | bash ask.sh
How many copies [1-10]: ten is not a number from 1 to 10
How many copies [1-10]: 0 is not a number from 1 to 10
How many copies [1-10]: making 7 copies
$ printf 'x\n\n99\n' | bash ask.sh
How many copies [1-10]: x is not a number from 1 to 10
How many copies [1-10]: '' is not a number from 1 to 10
How many copies [1-10]: 99 is not a number from 1 to 10
too many invalid answers
$ bash ask.sh < /dev/null
How many copies [1-10]:
no answer (end of input)

The last two runs ended with status 1. An empty answer is shown as '', which makes it clear that the person just pressed Enter. Lesson 134 builds whole menus on this kind of loop.

A Complete Example

tempconv.sh converts temperatures. It requires --from and --to, accepts negative values without --, expands abbreviated long options, suggests corrections for typos, reports all validation problems together, and separates usage errors (status 2) from data errors (status 1).

#!/usr/bin/env bash
# tempconv.sh - convert temperatures between Celsius, Fahrenheit and Kelvin
set -euo pipefail
prog=${0##*/}
long_opts=(from to precision verbose version help)

usage() {
    cat <<USAGE
Usage: $prog -f UNIT -t UNIT [-p DIGITS] [-v] VALUE...
Convert each VALUE from one temperature unit to another.
UNIT is c (Celsius), f (Fahrenheit) or k (Kelvin).

Options:
  -f, --from UNIT        unit of the input values (required)
  -t, --to UNIT          unit of the results (required)
  -p, --precision N      digits after the decimal point, 0-6 (default: 1)
  -v, --verbose          print "VALUE UNIT = RESULT UNIT"
  -h, --help             show this help and exit
      --version          show version information and exit

Long options may be shortened to any unique prefix (--prec).
Negative values can be given directly: $prog -f c -t f -40
USAGE
}
fail_usage() {     # fail_usage MESSAGE...: one line per message, then the hint
    local msg
    for msg in "$@"; do printf '%s: %s\n' "$prog" "$msg" >&2; done
    printf "Try '%s --help' for more information.\n" "$prog" >&2
    exit 2
}
show() {           # quote a value for a message; make control characters visible
    if [[ $1 == *[![:print:]]* ]]; then printf '%q' "$1"; else printf "'%s'" "$1"; fi
}

# distance A B: Levenshtein edit distance (insertions, deletions, substitutions)
distance() {
    local a=$1 b=$2 i j cost best
    local -a prev cur
    for (( j = 0; j <= ${#b}; j++ )); do prev[j]=$j; done
    for (( i = 1; i <= ${#a}; i++ )); do
        cur=("$i")
        for (( j = 1; j <= ${#b}; j++ )); do
            cost=1
            [[ ${a:i-1:1} == "${b:j-1:1}" ]] && cost=0
            best=$(( prev[j] + 1 ))
            (( cur[j-1] + 1 < best )) && best=$(( cur[j-1] + 1 ))
            (( prev[j-1] + cost < best )) && best=$(( prev[j-1] + cost ))
            cur[j]=$best
        done
        prev=("${cur[@]}")
    done
    echo "${prev[${#b}]}"
}

# expand_long NAME: print the full option name for NAME or a unique prefix of it
expand_long() {
    local name=$1 opt d best=99 guess= matches=()
    for opt in "${long_opts[@]}"; do
        [[ $opt == "$name" ]] && { echo "$opt"; return 0; }
        [[ $opt == "$name"* ]] && matches+=("$opt")
    done
    if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
    if (( ${#matches[@]} > 1 )); then
        fail_usage "option '--$name' is ambiguous; possibilities:$(printf " '--%s'" "${matches[@]}")"
    fi
    for opt in "${long_opts[@]}"; do
        d=$(distance "$name" "$opt")
        if (( d < best )); then best=$d guess=$opt; fi
    done
    if (( best <= 2 )); then
        fail_usage "unknown option '--$name'" "did you mean '--$guess'?"
    fi
    fail_usage "unknown option '--$name'"
}

from= to= precision=1 verbose=0
values=()
while (( $# > 0 )); do
    arg=$1
    if [[ $arg =~ ^-[0-9]+(\.[0-9]+)?$ ]]; then       # a negative number, not an option
        values+=("$arg"); shift; continue
    fi
    if [[ $arg == --?* ]]; then                       # --name or --name=value
        name=${arg#--}; name=${name%%=*}
        full=$(expand_long "$name") || exit
        [[ $arg == *=* ]] && arg="--$full=${arg#*=}" || arg="--$full"
    fi
    case $arg in
        -h|--help)          usage; exit 0 ;;
        -f|--from|-t|--to|-p|--precision)
                            (( $# > 1 )) || fail_usage "option '$1' requires an argument"
                            case $arg in
                                -f|--from) from=$2 ;;
                                -t|--to)   to=$2 ;;
                                *)         precision=$2 ;;
                            esac
                            shift ;;
        --from=*)           from=${arg#*=} ;;
        --to=*)             to=${arg#*=} ;;
        --precision=*)      precision=${arg#*=} ;;
        -v|--verbose)       verbose=1 ;;
        --version)          echo "$prog 1.0"; exit 0 ;;
        --verbose=*|--version=*|--help=*)
                            fail_usage "option '${arg%%=*}' does not take a value" ;;
        --)                 shift; values+=("$@"); break ;;
        -?*)                fail_usage "unknown option $(show "$arg")" ;;
        *)                  values+=("$arg") ;;
    esac
    shift
done

# Check everything and report all problems together.
errors=()
from=${from,,} to=${to,,}
[[ -n $from ]] || errors+=("missing required option '--from'")
[[ -n $to ]]   || errors+=("missing required option '--to'")
for u in from to; do
    v=${!u}
    if [[ -n $v && $v != [cfk] ]]; then
        errors+=("invalid --$u unit $(show "$v") (expected c, f or k)")
    fi
done
if [[ -n $from && $from == "$to" ]]; then
    errors+=("--from and --to are both '$from'; nothing to convert")
fi
[[ $precision =~ ^[0-6]$ ]] || errors+=("invalid precision $(show "$precision") (expected 0-6)")
(( ${#values[@]} > 0 )) || errors+=("no VALUE given")
for v in "${values[@]}"; do
    [[ $v =~ ^-?[0-9]+(\.[0-9]+)?$ ]] || errors+=("invalid VALUE $(show "$v") (expected a number such as 21 or -3.5)")
done
(( ${#errors[@]} == 0 )) || fail_usage "${errors[@]}"

# Convert. A value below absolute zero is a data error: report it, go on, exit 1 at the end.
status=0
for v in "${values[@]}"; do
    if ! result=$(awk -v v="$v" -v f="$from" -v t="$to" -v p="$precision" 'BEGIN {
            c = (f == "c") ? v : (f == "f") ? (v - 32) * 5 / 9 : v - 273.15
            if (c < -273.15) exit 3
            r = (t == "c") ? c : (t == "f") ? c * 9 / 5 + 32 : c + 273.15
            printf "%." p "f\n", r
        }'); then
        printf '%s: %s %s is below absolute zero\n' "$prog" "$v" "${from^^}" >&2
        status=1
        continue
    fi
    if (( verbose )); then
        printf '%s %s = %s %s\n' "$v" "${from^^}" "$result" "${to^^}"
    else
        printf '%s\n' "$result"
    fi
done
exit "$status"

How It Works

  • Negative numbers are checked first in each pass of the loop, so -40 never reaches the option branches.
  • Long options are normalized by expand_long before the case statement: --prec=2 becomes --precision=2 and --verb becomes --verbose. The case therefore needs only the full names. Short options are not abbreviated, so they skip this step.
  • One branch handles the three options that take a value. It checks that a value exists, and an inner case stores it in the right variable.
  • --verbose=yes is rejected explicitly. Without that branch it would fall through to -?* and be reported as unknown, which is technically true but less helpful.
  • Validation runs after parsing and collects every problem, including combinations (--from equal to --to). Unit letters are lowercased with ${from,,} first, so -f C is accepted; the indirect expansion ${!u} reads the variable whose name is in u (lesson 152 covers it in detail).
  • The conversion goes through Celsius. awk converts the input to Celsius, checks it against absolute zero (-273.15 °C), converts it to the target unit, and prints it with the requested number of decimals. Bash itself has only integer arithmetic (lesson 49). The format string is built from the precision, so "%." p "f\n" becomes "%.2f\n" for -p 2.
  • A value below absolute zero is a data error. awk exits with status 3, the script prints a message without the --help hint, skips that value, and exits with 1 after processing the rest.

Running the Complete Example

Normal conversions, including a negative value, the = form, an abbreviation and a separate value for --to:

$ bash tempconv.sh -f c -t f 100 37 -40
212.0
98.6
-40.0
$ bash tempconv.sh -v --from=f --to c 98.6 32
98.6 F = 37.0 C
32 F = 0.0 C
$ bash tempconv.sh --prec 2 -f c -t k -v 21.5
21.5 C = 294.65 K

A data error in the middle of a list. The other values are still converted, and the status is 1:

$ bash tempconv.sh -f k -t c -p 2 0 -5 300
-273.15
tempconv.sh: -5 K is below absolute zero
26.85

Usage errors, each ending with status 2 before any conversion:

$ bash tempconv.sh -f c -t f -x 20
tempconv.sh: unknown option '-x'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --colour 20
tempconv.sh: unknown option '--colour'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --verbose=yes 20
tempconv.sh: option '--verbose' does not take a value
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f C -t c 20
tempconv.sh: --from and --to are both 'c'; nothing to convert
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh 20
tempconv.sh: missing required option '--from'
tempconv.sh: missing required option '--to'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f
tempconv.sh: no VALUE given
Try 'tempconv.sh --help' for more information.

The suggestion, ambiguity and odd-input cases were shown in the sections above. Taken together, every message names the script, quotes the offending value in a safe form, says what was expected, and appears before the script has done any work.

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 Unknown Options and Invalid Input and get answers drawn from it.

Signed-in readers only.