Creating Interactive Menus in Bash

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

An interactive menu shows the user a list of actions, reads a choice, performs it, and shows the list again until the user quits. Menus are useful for scripts that people run by hand and that offer several related tasks: a small administration toolkit, a notes manager, a deployment helper for a team that does not want to remember options. Instead of reading the help and typing notes.sh --delete 2, the user just picks from what is on the screen.

Lesson 86 showed the select command, which builds a numbered menu automatically. This lesson builds menus by hand with while, read and case, which gives full control over the layout, the keys the user can press, the error messages and the flow between menus. It covers the basic menu loop, single-key input, yes/no confirmations with a default, menus built from data, submenus, an arrow-key menu, and how a menu script should behave when there is no person at the keyboard.

The Basic Menu Loop

Every hand-built menu has the same structure: an endless loop that prints the choices, reads one line, and dispatches it with case.

#!/usr/bin/env bash
while true; do
    echo
    echo "=== Main menu ==="
    echo "1) Show date"
    echo "2) Show logged-in user"
    echo "3) Count files here"
    echo "q) Quit"
    printf 'Choose an option: '
    IFS= read -r choice || { echo; break; }
    case $choice in
        1) date '+%A %d %B %Y' ;;
        2) id -un ;;
        3) files=(*); echo "${#files[@]} entries" ;;
        q|Q) echo "Bye."; break ;;
        '') ;;
        *) echo "'$choice' is not a valid choice" ;;
    esac
done

The parts and why they are there:

  • while true repeats until something inside the loop leaves it with break (or exit).
  • printf 'Choose an option: ' prints the prompt without a newline, so the answer is typed on the same line. read -p can print the prompt too, but it shows it only when the input comes from a terminal (lesson 31); printf always shows it, which also makes the menu easier to test.
  • IFS= read -r choice reads one whole line exactly as typed (lesson 114).
  • || { echo; break; } handles the end of input. When the user presses Ctrl + D, or a pipe runs out of lines, read fails. Without this check, the loop would print the menu again forever (lesson 87).
  • case maps each answer to an action. Accepting both q and Q costs nothing and saves the user a retry. An empty answer ('') just shows the menu again, and everything else gets a clear message.

The following run used piped input, so the answers (1, 7, an empty line, 3, q) do not appear after the prompts; on a terminal they would be visible where the user typed them:

$ printf '1\n7\n\n3\nq\n' | bash basic.sh

=== Main menu ===
1) Show date
2) Show logged-in user
3) Count files here
q) Quit
Choose an option: Sunday 22 November 2026

=== Main menu ===
...
Choose an option: '7' is not a valid choice

=== Main menu ===
...
Choose an option:
=== Main menu ===
...
Choose an option: 4 entries

=== Main menu ===
...
Choose an option: Bye.

(The repeated menu lines are shortened to ... here.) When the input ended without q, the loop left through the read check, and the script ended with status 0 instead of looping.

Pressing a Single Key

For short menus, making the user press Enter after every choice feels slow. read -n 1 returns as soon as one character has been typed, and -s (silent) stops the character from being echoed:

printf 'Continue? [y/N] '
IFS= read -rsn1 key
echo
case $key in [yY]) echo "yes";; *) echo "no (got '$key')";; esac
$ printf 'y' | bash key.sh
Continue? [y/N]
yes
$ printf '\n' | bash key.sh
Continue? [y/N]
no (got '')

Pressing Enter gives an empty key, because the newline ends the read and is not stored. The echo after read moves to a new line, which the user's own Enter would otherwise have done. Single-key input has one cost: a mistyped key is acted on immediately, with no chance to correct it, so it suits harmless choices ("next page", "show details") better than destructive ones.

Yes/No Confirmations with a Default

Before deleting or overwriting anything, a menu should ask for confirmation. By convention, the capital letter in [y/N] shows the default, which is used when the user just presses Enter:

# confirm QUESTION [DEFAULT]: ask a yes/no question; DEFAULT is y or n (n if not given)
confirm() {
    local question=$1 default=${2:-n} hint reply
    [[ $default == y ]] && hint='[Y/n]' || hint='[y/N]'
    while true; do
        printf '%s %s ' "$question" "$hint" >&2
        IFS= read -r reply || { echo >&2; return 1; }    # end of input counts as no
        reply=${reply,,}
        case ${reply:-$default} in
            y|yes) return 0 ;;
            n|no)  return 1 ;;
            *)     echo "Please answer y or n." >&2 ;;
        esac
    done
}
if confirm "Delete 3 old files?"; then echo "deleting"; else echo "kept"; fi
if confirm "Keep a backup?" y; then echo "backup on"; else echo "backup off"; fi

The function returns a status instead of printing an answer, so it can be used directly in if (lesson 90). ${reply,,} lowercases the answer (Bash 4.0 and later), so Y, YES and Yes all work. ${reply:-$default} replaces an empty answer with the default (lesson 132). Anything else asks again.

$ printf '\nn\n' | bash confirm.sh
Delete 3 old files? [y/N] kept
Keep a backup? [Y/n] backup off
$ printf 'maybe\nYES\nNo\n' | bash confirm.sh
Delete 3 old files? [y/N] Please answer y or n.
Delete 3 old files? [y/N] deleting
Keep a backup? [Y/n] backup off
$ printf '' | bash confirm.sh
Delete 3 old files? [y/N]
kept
Keep a backup? [Y/n]
backup off

In the first run, the empty answer took the default "no" for the first question. The last run shows a deliberate choice: when input ends, the answer is "no" even for the question whose default is "yes". If nobody can answer, the safe interpretation is that nobody agreed.

Often the choices are not fixed: a list of files, servers or saved notes. The menu is then printed from an array, and the answer must be checked against the current number of items:

print_notes() {                               # print_notes [INDEX...]: numbered list
    local i
    (( $# > 0 )) || set -- "${!notes[@]}"
    for i in "$@"; do
        printf '%3d) %s\n' "$((i + 1))" "${notes[i]#*|}"
    done
}
while true; do
    ask "Number to delete (Enter to cancel): "
    n=$REPLY
    [[ -z $n ]] && { say "Cancelled."; return; }
    if [[ $n =~ ^[0-9]+$ ]] && (( 10#$n >= 1 && 10#$n <= ${#notes[@]} )); then
        n=$((10#$n)); break
    fi
    say "Please enter a number from 1 to ${#notes[@]}."
done

People count from 1 and arrays from 0, so the printed number is the index plus one, and the chosen number minus one is the index (notes[n-1]). The check accepts only digits and only numbers inside the range; 10# keeps an answer such as 08 from being read as an invalid octal number (lesson 128). An empty answer is a way out, because a user who opened the wrong menu should never be forced to delete something. Both snippets come from the complete example below, where ask and say are defined.

A submenu is simply another menu loop inside a function. Choosing it from the main menu calls the function; leaving it with return goes back to the main loop, which prints the main menu again:

settings_menu() {
    while true; do
        say ""
        say "--- Settings ---"
        say "1) Show dates in lists: $( (( show_dates )) && echo on || echo off)"
        say "b) Back to main menu"
        ask "Choose: "
        case $REPLY in
            1)   show_dates=$(( ! show_dates )) ;;
            b|B) return ;;
            *)   say "Unknown choice '$REPLY'." ;;
        esac
    done
}

return leaves only the function (and therefore only the submenu's loop), while exit would end the whole program. Each menu shows the current value of its settings ("on" or "off"), so the user can see the effect of a choice immediately. $(( ! show_dates )) turns 1 into 0 and 0 into 1.

Clearing the Screen

Long sessions scroll old menus off the screen, and some scripts clear it before each menu. clear does this by printing control sequences:

$ TERM=xterm clear | od -c | head -1
0000000 033   [   H 033   [   2   J 033   [   3   J

\033[H moves the cursor to the top left corner, \033[2J clears the screen, and \033[3J clears the scrollback buffer as well. These bytes are only meaningful on a terminal. Written to a file or a pipe, they are junk, so a script should clear only when its output really is a terminal:

[[ -t 1 ]] && clear

Clearing also erases messages the user may still want to read, such as "Deleted." or a search result. Many menu scripts therefore clear only once at the start, or after a "Press Enter to continue" prompt.

An Arrow-Key Menu

A menu where the user moves a highlight with the arrow keys and presses Enter needs two techniques: reading the multi-byte sequences that arrow keys send, and redrawing the menu in place.

#!/usr/bin/env bash
# choose ITEM...: draw ITEMs on standard error, move with the arrow keys (or j/k),
# select with Enter. Prints the chosen item; returns 1 on q or end of input.
choose() {
    local items=("$@") cur=0 key rest i
    while true; do
        for i in "${!items[@]}"; do
            if (( i == cur )); then
                printf '> \e[7m%s\e[0m\e[K\n' "${items[i]}" >&2   # reverse video
            else
                printf '  %s\e[K\n' "${items[i]}" >&2
            fi
        done
        IFS= read -rsn1 key || return 1
        if [[ $key == $'\e' ]]; then                 # arrow keys send ESC [ A/B
            IFS= read -rsn2 -t 0.1 rest || true
            key+=$rest
        fi
        case $key in
            $'\e[A'|k) (( cur > 0 )) && cur=$((cur - 1)) ;;
            $'\e[B'|j) (( cur < ${#items[@]} - 1 )) && cur=$((cur + 1)) ;;
            '')        printf '%s\n' "${items[cur]}"; return 0 ;;
            q)         return 1 ;;
        esac
        printf '\e[%dA' "${#items[@]}" >&2            # cursor up: redraw in place
    done
}
if pick=$(choose "Start service" "Stop service" "Show status" "Quit"); then
    echo "You chose: $pick"
else
    echo "Cancelled"
fi

How it works:

  • Arrow keys send escape sequences. On common terminals, Up sends the three bytes ESC [ A and Down sends ESC [ B. The function reads one byte; if it is ESC ($'\e'), it reads up to two more with a short timeout (-t 0.1) and joins them. The timeout stops the menu from waiting forever when the user presses the Esc key alone, which sends only one byte.
  • j and k are accepted as well, like in vi and less, for terminals where the arrow keys send something else.
  • The highlight uses the SGR codes \e[7m (reverse video) and \e[0m (back to normal). \e[K clears the rest of each line, so a shorter line does not leave pieces of an old one behind.
  • Redrawing: after each key, \e[NA moves the cursor up N lines, to the start of the menu, and the next pass of the loop overwrites it.
  • The menu is drawn on standard error, and only the chosen item is printed on standard output. That is why pick=$(choose ...) captures just the item while the menu is still visible on the screen.

The tests fed the key sequences through a pipe, with the menu discarded:

$ printf '\e[B\e[B\n' | bash choose.sh 2>/dev/null
You chose: Show status
$ printf '\e[B\e[B\e[B\e[B\e[Akj\n' | bash choose.sh 2>/dev/null
You chose: Show status
$ printf 'jq' | bash choose.sh 2>/dev/null
Cancelled

In the second run, the fourth Down was ignored at the last item, Up and k moved back to the second item, and j moved to the third. What the menu writes for one Down press, made visible with cat -v (which shows ESC as ^[):

$ printf '\e[B\n' | bash choose.sh 2>&1 >/dev/null | cat -v
> ^[[7mStart service^[[0m^[[K
  Stop service^[[K
  Show status^[[K
  Quit^[[K
^[[4A  Start service^[[K
> ^[[7mStop service^[[0m^[[K
  Show status^[[K
  Quit^[[K

On a terminal, this appears as one menu whose highlight moves from the first line to the second; ^[[4A is the jump back up. These codes are the widely supported ANSI/VT100 sequences; tput rev and tput sgr0 look up the right codes for the current terminal type in the terminfo database, which is more portable when a script must work on unusual terminals.

Full-screen dialog boxes are also available through the external programs whiptail and dialog, which draw menus, checklists and input boxes. They are installed on many Debian and Ubuntu systems (whiptail) but not everywhere; neither was installed in the system used to test this lesson, so they are only mentioned here.

When There Is No Person at the Keyboard

A menu waits for a human. Started from cron, a CI job or another script, it either waits for input that never comes or reads garbage from a pipe. There are two common reactions.

Refuse to run without a terminal:

if [[ ! -t 0 || ! -t 1 ]]; then
    echo "guard.sh: this menu needs a terminal; use the command-line options instead" >&2
    exit 2
fi
$ bash guard.sh < /dev/null
guard.sh: this menu needs a terminal; use the command-line options instead

-t 0 and -t 1 test whether standard input and standard output are terminals (lesson 72). Run inside a terminal (the test used script, which provides one), the same script passed the check and exited with status 0.

Handle the end of input cleanly. Every read in the menu checks for failure and leaves the program, as in the basic loop above. This keeps the script testable with piped input, which is how every example in this lesson was tested. The complete example takes this approach.

A good design offers both interfaces: a menu for people and command-line options for automation (lessons 127 to 133), with the same functions doing the actual work.

A Complete Example

notes.sh is a small notes manager. Notes are stored one per line in a text file, as date|text. The main menu offers adding, listing, searching and deleting notes, and a settings submenu.

#!/usr/bin/env bash
# notes.sh - a small menu-driven notes manager
set -uo pipefail
notes_file=${NOTES_FILE:-$HOME/notes.txt}
show_dates=1

say()  { printf '%s\n' "$*" >&2; }            # menus and messages: standard error
ask()  {                                      # ask PROMPT: read one line into REPLY
    printf '%s' "$1" >&2
    IFS= read -r REPLY && return 0
    [[ -n $REPLY ]] && return 0               # last line without a newline
    say ""; say "End of input, leaving."; exit 0
}
confirm() {                                   # confirm QUESTION: default is no
    ask "$1 [y/N] "
    [[ ${REPLY,,} == y || ${REPLY,,} == yes ]]
}
load_notes() {                                # read the file into the array notes
    notes=()
    [[ -f $notes_file ]] && mapfile -t notes < "$notes_file"
    return 0
}
print_notes() {                               # print_notes [INDEX...]: numbered list
    local i
    (( $# > 0 )) || set -- "${!notes[@]}"
    for i in "$@"; do
        if (( show_dates )); then
            printf '%3d) %s  %s\n' "$((i + 1))" "${notes[i]%%|*}" "${notes[i]#*|}"
        else
            printf '%3d) %s\n' "$((i + 1))" "${notes[i]#*|}"
        fi
    done
}

add_note() {
    ask "Note text (empty to cancel): "
    local text=$REPLY
    text=${text//$'\t'/ }                     # keep the file one note per line
    if [[ -z ${text// /} ]]; then say "Nothing added."; return; fi
    printf '%s|%s\n' "$(date +%F)" "$text" >> "$notes_file"
    say "Added."
}
list_notes() {
    load_notes
    if (( ${#notes[@]} == 0 )); then say "No notes yet."; return; fi
    print_notes
}
search_notes() {
    ask "Search for: "
    local word=$REPLY i text hits=()
    [[ -n $word ]] || { say "Nothing to search for."; return; }
    load_notes
    for i in "${!notes[@]}"; do
        text=${notes[i]#*|}
        [[ ${text,,} == *"${word,,}"* ]] && hits+=("$i")   # ignore case
    done
    if (( ${#hits[@]} == 0 )); then say "No note contains '$word'."; return; fi
    print_notes "${hits[@]}"
    say "${#hits[@]} match(es)."
}
delete_note() {
    load_notes
    if (( ${#notes[@]} == 0 )); then say "No notes to delete."; return; fi
    print_notes
    local n
    while true; do
        ask "Number to delete (Enter to cancel): "
        n=$REPLY
        [[ -z $n ]] && { say "Cancelled."; return; }
        if [[ $n =~ ^[0-9]+$ ]] && (( 10#$n >= 1 && 10#$n <= ${#notes[@]} )); then
            n=$((10#$n)); break
        fi
        say "Please enter a number from 1 to ${#notes[@]}."
    done
    confirm "Delete note $n: '${notes[n-1]#*|}'?" || { say "Kept."; return; }
    unset 'notes[n-1]'
    if (( ${#notes[@]} > 0 )); then
        printf '%s\n' "${notes[@]}" > "$notes_file.tmp"
    else
        : > "$notes_file.tmp"
    fi
    mv -- "$notes_file.tmp" "$notes_file"
    say "Deleted."
}
settings_menu() {
    while true; do
        say ""
        say "--- Settings ---"
        say "1) Show dates in lists: $( (( show_dates )) && echo on || echo off)"
        say "b) Back to main menu"
        ask "Choose: "
        case $REPLY in
            1)   show_dates=$(( ! show_dates )) ;;
            b|B) return ;;
            *)   say "Unknown choice '$REPLY'." ;;
        esac
    done
}

[[ -t 1 ]] && clear
while true; do
    load_notes
    say ""
    say "=== Notes (${#notes[@]} saved in $notes_file) ==="
    say "1) Add a note      2) List notes"
    say "3) Search notes    4) Delete a note"
    say "5) Settings        q) Quit"
    ask "Choose an option: "
    case ${REPLY,,} in
        1|a|add)    add_note ;;
        2|l|list)   list_notes ;;
        3|s|search) search_notes ;;
        4|d|delete) delete_note ;;
        5)          settings_menu ;;
        q|quit)     say "Bye."; exit 0 ;;
        '')         ;;
        *)          say "'$REPLY' is not a menu option." ;;
    esac
done

How It Works

  • ask is the only place that reads input. It prints the prompt, stores the answer in REPLY, and ends the program cleanly at the end of input, so no menu can loop forever.
  • say writes menus and messages to standard error; the lists themselves go to standard output. Running notes.sh 2>/dev/null therefore leaves only the notes, which keeps the results usable in a pipe while the menu stays on the screen.
  • Each action is a function, and the main case only dispatches. Adding a menu entry means adding one function and one case line. The case accepts numbers, first letters and words (2, l, list), lowercased with ${REPLY,,}.
  • The note count is reloaded before each main menu, so the heading is always current, even if another program changed the file.
  • Adding replaces tabs with spaces and rejects text that is empty or only spaces, so every line in the file is one real note.
  • Searching compares lowercased copies, so MILK finds "Buy milk".
  • Deleting validates the number, shows the note's text in the confirmation, and writes the remaining notes to a temporary file that replaces the original with mv (lesson 113 discusses safer temporary names). unset 'notes[n-1]' leaves a gap in the array, which does not matter here because "${notes[@]}" skips it (lesson 99).
  • set -e is not used. A menu script runs many tests whose "false" result is normal (an empty search, a declined confirmation), and every one of them would need special care under set -e (lesson 119). set -u and pipefail are kept.
  • NOTES_FILE lets the user choose another file, with ~/notes.txt as the default (lesson 132).

Running the Complete Example

The session below was run with HOME=/home/ana and piped input. The typed answers are shown in brackets after each prompt so the session can be followed; in a real terminal they would simply appear where the user typed them. Repeated main menus are shortened.

=== Notes (0 saved in /home/ana/notes.txt) ===
1) Add a note      2) List notes
3) Search notes    4) Delete a note
5) Settings        q) Quit
Choose an option: [1]
Note text (empty to cancel): [Buy milk]
Added.
...
Choose an option: [1]
Note text (empty to cancel): [   ]
Nothing added.
...
Choose an option: [a]
Note text (empty to cancel): [Renew domain gocourse]
Added.

=== Notes (3 saved in /home/ana/notes.txt) ===
...
Choose an option: [2]
  1) 2026-11-22  Buy milk
  2) 2026-11-22  Call the bank about the card
  3) 2026-11-22  Renew domain gocourse
...
Choose an option: [7]
'7' is not a menu option.
...
Choose an option: [3]
Search for: [MILK]
  1) 2026-11-22  Buy milk
1 match(es).

(The second note, "Call the bank about the card", was added in the same way before the empty one.) Deleting asks for a valid number and a confirmation; the first attempt below is declined, the second accepted:

Choose an option: [4]
  1) 2026-11-22  Buy milk
  2) 2026-11-22  Call the bank about the card
  3) 2026-11-22  Renew domain gocourse
Number to delete (Enter to cancel): [9]
Please enter a number from 1 to 3.
Number to delete (Enter to cancel): [2]
Delete note 2: 'Call the bank about the card'? [y/N] [n]
Kept.
...
Choose an option: [4]
...
Number to delete (Enter to cancel): [2]
Delete note 2: 'Call the bank about the card'? [y/N] [y]
Deleted.

=== Notes (2 saved in /home/ana/notes.txt) ===

The settings submenu turns the dates off, and the next list uses the new setting:

Choose an option: [5]

--- Settings ---
1) Show dates in lists: on
b) Back to main menu
Choose: [1]

--- Settings ---
1) Show dates in lists: off
b) Back to main menu
Choose: [b]

=== Notes (2 saved in /home/ana/notes.txt) ===
...
Choose an option: [l]
  1) Buy milk
  2) Renew domain gocourse
...
Choose an option: [q]
Bye.

The file now holds the two remaining notes:

2026-11-22|Buy milk
2026-11-22|Renew domain gocourse

When the input ends in the middle of a question, the program says so and stops with status 0 instead of waiting or looping:

$ printf '3\n' | bash notes.sh
...
Choose an option: Search for:
End of input, leaving.

Because the lists go to standard output, they can be separated from the menu:

$ printf '2\nq\n' | bash notes.sh 2>/dev/null
  1) 2026-11-22  Buy milk
  2) 2026-11-22  Renew domain gocourse

The dates in your notes will be the day you add them. With this lesson, the section on arguments and command-line interfaces is complete; the next section turns to processes, starting with the difference between foreground and background processes.

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 Creating Interactive Menus in Bash and get answers drawn from it.

Signed-in readers only.