shBash
BeginnerLesson 3 of 15

Variables, Quoting & Arithmetic – Bash

Store values, set quotes correctly, command output and arithmetic.

You assign variables without spaces around the = and read them with $ (or ${name} to delimit the name). There is only text – numbers are text that gets interpreted as a number when needed.

name="Ada"                 # NO spaces around =
alter=36
echo "Hello $name, you are $alter"     # Hello Ada, you are 36
echo 'Hello $name'                     # Hello $name   (single quotes: everything literal)
datei="bericht"
echo "${datei}_final.txt"              # bericht_final.txt  (braces delimit the name)

With $(command) you capture a command output in a variable (command substitution). With $(( )) you calculate with integers. For default values there is the parameter expansion ${var:-default}.

heute=$(date +%F)              # e.g. 2024-05-01
anzahl=$(ls | wc -l)
echo "Today is $heute, there are $anzahl entries"

echo $((3 + 4 * 2))            # 11
echo $((7 / 2)) $((7 % 2))     # 3 1   (integers only!)
x=5; x=$((x + 1)); echo "$x"   # 6
echo "${gast:-Guest}"            # Guest   (if "gast" is empty/unset)

Environment variables are variables that are inherited by child processes – with export. You read input with read. Important predefined variables: $HOME, $USER, $PWD, $PATH, $? (exit code of the last command), $$ (own PID), $0 (script name).

export APP_ENV=produktion     # visible to child processes
APP_ENV=test ./deploy.sh       # set only for this one call
read -r -p "What is your name? " eingabe
echo "Hi $eingabe"
echo "$PATH" | tr ':' '\n'      # show PATH line by line
WarningAlmost always put variables in double quotes: "$datei". Without quotes the shell splits the content at spaces and applies wildcards: rm $datei with datei="Mein Bericht.txt" deletes two files named Mein and Bericht.txt.
Tipreadonly PI=3.14 creates a constant, declare -i n=5 enforces integers, unset name removes the variable. Variable names: lowercase for local ones, UPPERCASE for environment/constants.