Bash Scripting FundamentalsLesson 3.2
Bash variables and how to use them
variable assignment, quoting rules, environment variables, readonly, unset, command substitution, arithmetic, special variables $0 $1 $#
Variables Store Values for Reuse
Bash variables hold strings. There are no types — everything is a string unless you use arithmetic context. The rules around quoting are the number one source of bugs in Bash scripts.
Assignment and Referencing
No spaces around = when assigning. Always quote variable references with double quotes to prevent word splitting when the value contains spaces.
#!/bin/bash
# Assign (no spaces around =)
NAME="Alice"
PROJECT_DIR="/home/alice/projects"
DATE=$(date +%Y-%m-%d) # command substitution
# Reference with $
echo "Hello, $NAME"
echo "Today is $DATE"
# Quote to handle spaces safely
FILE="my document.txt"
ls -l "$FILE" # correct
ls -l $FILE # WRONG — splits on spaceSpecial Variables
#!/bin/bash
# $0 = script name
# $1, $2... = positional arguments
# $# = number of arguments
# $@ = all arguments as separate strings
# $? = exit code of last command
echo "Script: $0"
echo "First arg: $1"
echo "Arg count: $#"
# Arithmetic — must use (( )) or $(( ))
COUNT=5
echo $((COUNT + 3)) # prints 8
((COUNT++))
echo $COUNT # prints 6readonly VAR=value makes a variable immutable. unset VAR deletes it. export VAR makes it available to child processes as an environment variable.
