Variables

Hard-coding values makes scripts inflexible. Variables make them dynamic.

Creating Variables

Terminal
$name="John"
$age=30
$city="New York"

No Spaces Around =

name="John" โœ“ name = "John" โœ— (bash thinks "name" is a command)

Using Variables

Prefix with $ to access the value:

Terminal
$echo $name
John
$echo "Hello, $name"
Hello, John
$echo "$name is $age years old"
John is 30 years old

Curly Braces

Use ${} when the variable name could be ambiguous:

Terminal
$file="report"
$echo "$file_backup"
(empty - looks for variable 'file_backup')
$echo "${file}_backup"
report_backup

Always safe to use ${var} instead of $var.

Quoting Matters

Terminal
$greeting="Hello World"
$echo $greeting
Hello World
$
$# But with special characters:
$path="/home/user/my files"
$ls $path
ls: /home/user/my: No such file or directory
$ls "$path"
(works correctly)

Always Quote Variables

"$variable" handles spaces and special characters safely. Unquoted variables cause bugs.

Command Substitution

Store command output in a variable:

Terminal
$today=$(date)
$echo "Today is $today"
Today is Tue Jan 14 10:30:45 UTC 2025
$
$files=$(ls)
$echo "Files: $files"
Files: file1.txt file2.txt

$(command) runs the command and captures output.

Environment Variables

System-provided variables:

Terminal
$echo $HOME
/home/user
$echo $USER
user
$echo $PATH
/usr/local/bin:/usr/bin:/bin
$echo $PWD
/home/user/scripts
$echo $SHELL
/bin/bash
VariableContains
$HOMEHome directory
$USERCurrent username
$PATHExecutable search paths
$PWDCurrent directory
$SHELLDefault shell
$RANDOMRandom number

Export Variables

Make variables available to child processes:

Terminal
$export MY_VAR="important"
$bash -c 'echo $MY_VAR'
important
$
$# Without export:
$LOCAL_VAR="local"
$bash -c 'echo $LOCAL_VAR'
(empty)

Read-Only Variables

Protect variables from being changed:

Terminal
$readonly PI=3.14159
$PI=3
bash: PI: readonly variable

Practical Script

hljs bash
#!/bin/bash
# Deployment script with variables

APP_NAME="myapp"
VERSION="1.2.3"
DEPLOY_DIR="/var/www/${APP_NAME}"
BACKUP_DIR="/var/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo "Deploying $APP_NAME version $VERSION"
echo "Target: $DEPLOY_DIR"
echo "Backup: $BACKUP_DIR/${APP_NAME}_$TIMESTAMP"

# Create backup
cp -r "$DEPLOY_DIR" "$BACKUP_DIR/${APP_NAME}_$TIMESTAMP"

echo "Deployment complete!"
Knowledge Check

What is wrong with this code: name = John

Quick Reference

SyntaxPurpose
var="value"Create variable
$varUse variable
${var}Use (safer syntax)
"$var"Use with quoting
$(command)Command substitution
export varMake available to child processes
readonly varPrevent changes

Key Takeaways

  • No spaces around = when assigning
  • Use $var or ${var} to access values
  • Always quote variables: "$var"
  • $(command) captures command output
  • Environment variables like $HOME are preset
  • export shares variables with subprocesses

Next: getting input from users.