⚡
usefultools.dev
$_

Bash-Scripting-Spickzettel

NEU

Spickzettel für Bash-Skripte: Variablen, Quoting, Parameter-Expansion, if und case, Schleifen, Funktionen, Arrays, Exit-Codes, Umleitungen, trap und set -euo pipefail. Mit Suche und Kopieren. Die Befehle sind auf Englisch.

Läuft zu 100 % in deinem Browser — deine Eingaben werden nie hochgeladen oder auf unseren Servern gespeichert.

110 Einträge in 11 Abschnitten

Shebang & running scripts

  • #!/usr/bin/env bash

    First line of a script: run it with the bash found on PATH.

  • chmod +x script.sh

    Make the script executable.

  • ./script.sh

    Run an executable script from the current folder.

  • bash script.sh

    Run the script with bash without needing the executable bit.

  • source script.sh

    Run the script in the current shell so its variables and functions stay (. script.sh is the same).

  • bash -n script.sh

    Check the syntax without running anything.

  • bash -x script.sh

    Run with a trace that prints every command before it executes.

Variables & quoting

  • name="Ada"

    Assign a variable. No spaces around the = sign.

  • echo "$name"

    Use a variable. Double quotes keep spaces and prevent word splitting.

  • echo '$name'

    Single quotes print the text literally, with no expansion.

  • echo "${name}_backup"

    Braces mark where the variable name ends.

  • export API_URL="https://example.com"

    Make the variable visible to child processes.

  • readonly PI=3.14

    Make a variable constant.

  • today=$(date +%F)

    Command substitution: store a command's output in a variable.

  • echo $((3 + 4 * 2))

    Integer arithmetic expansion; prints 11.

Parameter expansion

  • ${var:-default}

    Use "default" if var is unset or empty.

  • ${var:=default}

    Same, and also assign the default to var.

  • ${var:?error message}

    Exit with the message if var is unset or empty.

  • ${var:+alt}

    Use "alt" only when var is set and not empty.

  • ${#var}

    Length of the value in characters.

  • ${var:2:3}

    Substring: three characters starting at offset 2 (offsets start at 0).

  • ${var#prefix}

    Remove the shortest match of prefix from the start.

  • ${var##*/}

    Remove the longest match from the start: the file name of a path.

  • ${var%suffix}

    Remove the shortest match of suffix from the end.

  • ${var%%.*}

    Remove the longest match from the end: strip every extension.

  • ${var/old/new}

    Replace the first match of old.

  • ${var//old/new}

    Replace all matches of old.

  • ${var^^} / ${var,,}

    Convert to UPPERCASE / lowercase (Bash 4+).

Conditionals & test operators

  • if [[ -f "$file" ]]; then echo "exists" elif [[ -d "$file" ]]; then echo "directory" else echo "missing" fi

    if / elif / else block.

  • [[ -e "$p" ]] [[ -f "$p" ]] [[ -d "$p" ]]

    Path exists / is a regular file / is a directory.

  • [[ -r "$p" ]] [[ -w "$p" ]] [[ -x "$p" ]]

    Path is readable / writable / executable.

  • [[ -s "$file" ]]

    File exists and is not empty.

  • [[ -z "$s" ]] [[ -n "$s" ]]

    String is empty / is not empty.

  • [[ "$a" == "$b" ]]

    String equality (use != for inequality).

  • [[ "$s" == *.txt ]]

    Glob pattern match; leave the pattern unquoted.

  • [[ "$s" =~ ^[0-9]+$ ]]

    Regular expression match.

  • [[ $a -eq $b ]]

    Number comparison: -eq -ne -lt -le -gt -ge.

  • (( a > b ))

    Arithmetic comparison using ordinary operators.

  • [[ -f "$f" && -r "$f" ]]

    Combine tests with && (and), || (or) and ! (not).

  • case "$1" in start) echo "starting" ;; stop|quit) echo "stopping" ;; *) echo "unknown" ;; esac

    Pattern-based branching.

Loops

  • for i in 1 2 3; do echo "$i"; done

    Loop over a list of words.

  • for i in {1..5}; do echo "$i"; done

    Loop over a numeric range (brace expansion).

  • for ((i = 0; i < 5; i++)); do echo "$i"; done

    C-style loop.

  • for f in *.txt; do echo "$f"; done

    Loop over files matching a glob.

  • for arg in "$@"; do echo "$arg"; done

    Loop over all script arguments.

  • while read -r line; do echo "$line"; done < file.txt

    Read a file line by line.

  • while true; do sleep 1; done

    Loop until the script is stopped or a break runs.

  • until ping -c1 -W1 example.com >/dev/null; do sleep 2; done

    Repeat until the command succeeds.

  • break / continue

    Leave the loop / skip to the next iteration.

Functions & arguments

  • greet() { echo "Hello, $1" }

    Define a function; its arguments are $1, $2 and so on.

  • greet Ada

    Call a function like a command, without parentheses.

  • local count=0

    Declare a variable that exists only inside the function.

  • return 1

    Leave a function with an exit status (0 to 255).

  • result=$(greet Ada)

    Capture what a function prints.

  • $1 $2 ... ${10}

    Positional arguments; use braces from the tenth on.

  • $#

    Number of arguments.

  • "$@"

    All arguments, each kept as a separate word (almost always the right choice).

  • shift

    Drop $1 and move the other arguments down by one.

  • $0

    Name of the script.

Arrays

  • arr=(apple banana cherry)

    Create an indexed array.

  • ${arr[0]}

    First element (indexes start at 0).

  • "${arr[@]}"

    All elements, each as its own word.

  • ${#arr[@]}

    Number of elements.

  • arr+=(date)

    Append an element.

  • "${arr[@]:1:2}"

    Slice: two elements starting at index 1.

  • ${!arr[@]}

    All indexes of the array.

  • declare -A colors

    Declare an associative array (Bash 4+).

  • colors[sky]=blue

    Set a key in an associative array.

  • ${colors[sky]}

    Read a value by key.

  • mapfile -t lines < file.txt

    Read a file into an array, one line per element (Bash 4+).

Exit codes & control operators

  • echo $?

    Exit status of the last command; 0 means success.

  • exit 1

    End the script with a status; non-zero signals failure.

  • cmd1 && cmd2

    Run cmd2 only if cmd1 succeeded.

  • cmd1 || cmd2

    Run cmd2 only if cmd1 failed.

  • cmd1; cmd2

    Run both commands one after the other, regardless of the result.

  • cmd &

    Run the command in the background.

  • wait

    Wait for all background jobs to finish.

  • ! cmd

    Invert the exit status.

  • command -v git >/dev/null || { echo "git is required" >&2; exit 1; }

    Check that a program is installed and stop with an error if it is not.

Redirection, pipes & here-docs

  • cmd > out.txt

    Write standard output to a file, replacing it.

  • cmd >> out.txt

    Append standard output to a file.

  • cmd 2> err.txt

    Write standard error to a file.

  • cmd > all.txt 2>&1

    Send standard output and standard error to the same file.

  • cmd > /dev/null 2>&1

    Discard all output.

  • echo "message" >&2

    Print to standard error.

  • cmd < input.txt

    Read standard input from a file.

  • cmd1 | cmd2

    Pipe the output of cmd1 into cmd2.

  • cmd | tee out.txt

    Show the output and also save it to a file.

  • diff <(sort a.txt) <(sort b.txt)

    Process substitution: use command output where a file is expected.

  • cat <<EOF Hello $USER EOF

    Here-document: multi-line input; variables are expanded.

  • cat <<'EOF' No $expansion here EOF

    Quote the delimiter to turn expansion off.

  • grep foo <<< "$text"

    Here-string: feed a string to standard input.

Safety, traps & options

  • set -euo pipefail

    Stop on errors (-e), on unset variables (-u) and on failures inside pipes (pipefail).

  • set -x

    Print each command as it runs (set +x turns it off).

  • IFS=$'\n\t'

    Split words only on newlines and tabs, not on spaces.

  • tmp=$(mktemp)

    Create a unique temporary file and keep its name.

  • trap 'rm -f "$tmp"' EXIT

    Run cleanup when the script exits, however it ends.

  • trap 'echo "interrupted"; exit 130' INT TERM

    React to Ctrl-C and termination signals.

  • while getopts "vf:h" opt; do case $opt in v) verbose=1 ;; f) file=$OPTARG ;; h) usage; exit 0 ;; *) exit 1 ;; esac done

    Parse flags: -v and -h are switches, -f takes a value (the colon).

  • shift $((OPTIND - 1))

    After getopts, remove the parsed flags so $1 is the first real argument.

Common one-liners

  • cd "$(dirname "$0")"

    Change to the folder the script lives in.

  • SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

    Absolute path of the script folder, also correct when the script is sourced.

  • read -rp "Continue? [y/N] " answer

    Ask the user a question and store the reply.

  • for f in *.txt; do mv -- "$f" "${f%.txt}.md"; done

    Rename every .txt file to .md.

  • find . -name "*.log" -mtime +7 -delete

    Delete .log files older than seven days.

  • find . -type f -print0 | xargs -0 wc -l

    Run a command on found files, safe for names with spaces.

  • grep -rn "TODO" .

    Search every file below the current folder and show line numbers.

  • sort file.txt | uniq -c | sort -nr

    Count duplicate lines, most frequent first.

  • du -sh * | sort -h

    Folder sizes, smallest to largest.

  • echo "$PATH" | tr ':' '\n'

    Print each PATH entry on its own line.

⚡

Schnelle Beispiele

Typische Eingaben und die Ergebnisse, die dieses Tool liefert.

Sicherheit
Ein Skript bei Fehlern anhalten lassen
set -euo pipefail
Einzeiler
Jede .txt-Datei in .md umbenennen
for f in *.txt; do mv -- "$f" "${f%.txt}.md"; done
Umleitung
Ausgabe und Fehler in eine Datei schreiben
cmd > all.txt 2>&1
Expansion
Einen Standardwert nutzen, wenn eine Variable leer ist
${var:-default}
📖

Überblick

Bash ist die Standard-Shell der meisten Linux-Server, und ein kurzes Skript kann Arbeit automatisieren, für die man sonst viele manuelle Schritte bräuchte. Dieser Bash-Spickzettel deckt die Syntax ab, die du zum Schreiben brauchst: die Shebang-Zeile, Variablen und Quoting, Parameter-Expansion, Tests und Bedingungen, Schleifen, Funktionen, Arrays, Exit-Codes und Umleitungen.

Außerdem enthält er Gewohnheiten, die Skripte sicherer machen, etwa set -euo pipefail, trap für das Aufräumen, getopts für Optionen und das Quoting von "$@". Ein Abschnitt am Ende bietet Einzeiler zum Umbenennen, Suchen und Zählen. Filtere die Liste und kopiere jedes Snippet mit einem Klick.

Befehle, Optionen und ihre Kurzbeschreibungen werden auf Englisch angezeigt, so wie du sie im Terminal siehst; übersetzt sind nur der Seitentext und die Oberfläche. Nichts, was du eingibst, verlässt deinen Browser.

Warum dieses Tool?

  • Finde die genaue Bash-Syntax, ohne Man-Pages zu durchsuchen
  • Quoting und Test-Operatoren in je einer Zeile erklärt
  • Sicherheitsoptionen und trap-Muster für zuverlässige Skripte
  • Filtern nach Stichwörtern wie loop, array oder redirect
  • Mehrzeilige Snippets werden samt Einrückung kopiert
⭐

Funktionen

🔍

Live-Filter

Gib ein Stichwort ein, um nur die passenden Snippets und Abschnitte zu sehen.

📋

Kopieren pro Snippet

Jede Zeile hat einen Kopieren-Button, der Zeilenumbrüche und Einrückung beibehält.

🧪

Test-Operatoren

Datei-, String- und Zahlenprüfungen für [[ ]] und (( )) an einem Ort.

🧵

Parameter-Expansion

Standardwerte, Teilstrings, Entfernen von Präfix und Suffix und Groß-/Kleinschreibung.

🛡️

Sicherheitsabschnitt

set -euo pipefail, trap, mktemp und getopts für verlässliche Skripte.

📱

Mobilfreundlich

Lange Snippets werden umbrochen, sodass die Zeilen auf dem Handy lesbar bleiben.

🛠️

So funktioniert’s

1

Abschnitt wählen

Scrolle zu Variables, Loops, Functions, Redirection oder einer anderen Gruppe (die Abschnittstitel sind auf Englisch).

2

Oder den Filter nutzen

Gib ein Wort wie „array“ oder „trap“ in das Feld „Diesen Spickzettel filtern“ ein.

3

Hinweis lesen

Die englischen Beschreibungen sagen, wann eine Funktion Bash 4 oder neuer braucht oder von reinem sh abweicht.

4

Kopieren und anpassen

Klicke auf Kopieren, füge es in dein Skript ein und ersetze die Beispielnamen und Pfade.

🤔

Häufig gestellte Fragen