shBash

Bash: More snippets – code examples

Contents

Hello World

Basics#echo#shebang#outputCompare in all languages
Use case: A first test that the terminal and shebang work.
#!/usr/bin/env bash
echo "Hello World!"

echo prints text. The shebang line determines that Bash runs the script; then chmod +x hallo.sh and ./hallo.sh.

Variables, Constants and Arithmetic

Basics#variable#readonly#arithmeticCompare in all languages
Use case: Store values in scripts, e.g. paths, counters or configuration.
name="Ada"
alter=36
readonly PI=3.14
echo "Name: $name, Age: $alter"
echo "Next year: $((alter + 1))"
echo "No value: ${unbekannt:-Standard}"
echo "Length of the name: ${#name}"

Assign without spaces around the =. Everything is text; $(( )) calculates with integers, ${var:-x} returns a default value and readonly protects constants.

if / elif / else with [[ ]]

Control flow#if#test#conditionCompare in all languages
Use case: React differently, e.g. check files, distinguish environments or validate input.
punkte=73
if [[ $punkte -ge 90 ]]; then
  echo "very good"
elif [[ $punkte -ge 70 ]]; then
  echo "good"
else
  echo "needs improvement"
fi

[[ ... ]] is the Bash test construct; you compare numbers with -ge, -lt, -eq … (text with ==, !=). Every block ends with fi.

for and while Loops

Control flow#for#while#loopCompare in all languages
Use case: Process several files or values one after another.
for i in 1 2 3; do
  echo "Round $i"
done

for frucht in Apple Pear; do
  echo "$frucht"
done

n=0
while (( n < 3 )); do
  echo "n=$n"
  n=$((n + 1))
done

for runs over a list of words (also {1..5} or *.txt), while as long as the condition holds. Blocks are formed with do … done.

Function with a Default Value

Functions#function#local#argumentsCompare in all languages
Use case: Define recurring tasks such as logging or checks once.
begruesse() {
  local name="$1"
  local gruss="${2:-Hello}"
  echo "$gruss, $name!"
}

begruesse "Ada"
begruesse "Linus" "Hi"

Functions read arguments via $1, $2 …; local prevents variables from leaking outwards. Values are returned via echo (text) or exit code (return).

Catching Errors: Strict Mode & trap

Error handling#set -e#trap#exit-code#errorCompare in all languages
Use case: Scripts that abort cleanly on errors and clean up temp files, e.g. in CI/CD or cron.
#!/usr/bin/env bash
set -euo pipefail

tmp=$(mktemp)
trap 'echo "Cleaning up"; rm -f "$tmp"' EXIT

echo "working ..." > "$tmp"
cp /gibt-es-nicht "$tmp" 2> /dev/null || echo "Copy failed, continuing"
echo "done"

set -euo pipefail aborts on errors, undefined variables and pipeline failures. trap … EXIT always cleans up. With || action you deliberately catch an expected error.

Use Temporary Files Safely

Error handling#mktemp#trap#temp
Use case: Store intermediate results without leftovers remaining if the script aborts.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

sort -u eingabe.txt > "$tmp/sortiert.txt"
wc -l < "$tmp/sortiert.txt"

mktemp -d creates a unique temp directory, trap … EXIT guarantees it is deleted – even on errors and Ctrl+C. No risk from fixed file names in /tmp.

Read a File Line by Line

Files#read#while#file#linesCompare in all languages
Use case: Process logs, lists or configurations line by line.
printf 'Line 1\nLine 2\nLine 3\n' > notizen.txt

nr=0
while IFS= read -r zeile; do
  nr=$((nr + 1))
  echo "$nr: $zeile"
done < notizen.txt

while read … done < file reads line by line. IFS= and -r preserve spaces and backslashes. Important: redirect the file with < instead of cat file | while … – the pipe would create a subshell and variables would be lost.

Rename Files in Bulk

Files#rename#mv#glob#parameter-expansion
Use case: Rename photos, exports or reports following a pattern (e.g. .jpeg to .jpg).
for f in *.jpeg; do
  [[ -e "$f" ]] || continue          # skip patterns without matches
  neu="${f%.jpeg}.jpg"
  echo "mv -- '$f' '$neu'"           # dry run: only display
  # mv -- "$f" "$neu"                # enable to actually run
done

${f%.jpeg} cuts off the suffix. The dry run with echo shows what would happen – only then enable the mv. -- protects against names that begin with -.