Bash: More snippets – code examples
Hello World
#!/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
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 [[ ]]
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
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))
donefor 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
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
#!/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
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
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.txtwhile 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
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 -.