Variables in Scripts
Variables store data that your scripts can use and manipulate. Understanding variables is essential for writing useful scripts.
Defining Variables
NAME="John"
AGE=25
FILE_PATH="/home/user/data.txt"
Rules:
- No spaces around
= - No
$when setting - Use
$when accessing
Using Variables
echo $NAME
echo "Hello, $NAME"
echo "Path: ${FILE_PATH}"
Quoting Variables
Always quote variables to handle spaces:
FILE="my file.txt"
cat "$FILE" # Correct
cat $FILE # Wrong - tries to cat "my" and "file.txt"
Special Variables
| Variable | Meaning |
|---|---|
$0 | Script name |
$1, $2... | Arguments |
$# | Number of arguments |
$@ | All arguments (as separate words) |
$* | All arguments (as single word) |
$? | Exit status of last command |
$$ | Current process ID |
$! | PID of last background process |
Command Line Arguments
#!/bin/bash
# Save as greet.sh
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of args: $#"
Run it:
./greet.sh Hello World
# Script name: ./greet.sh
# First argument: Hello
# Second argument: World
Exercise: Use Variables
Create and use a variable in the terminal:
Command Substitution
Capture command output in a variable:
# Modern syntax
DATE=$(date)
FILES=$(ls)
# Older syntax
DATE=`date`
Arithmetic
# Using $(( ))
SUM=$((5 + 3))
PRODUCT=$((4 * 7))
# Using let
let "COUNT = COUNT + 1"
let "COUNT++"
# Using expr (older)
RESULT=$(expr 5 + 3)
String Operations
NAME="Linux"
# Length
echo ${#NAME} # 5
# Substring
echo ${NAME:0:3} # Lin
# Replace
FILE="data.txt"
echo ${FILE/txt/csv} # data.csv
Default Values
# Use default if unset
echo ${NAME:-"Unknown"}
# Set default if unset
echo ${NAME:="Default"}
# Error if unset
echo ${NAME:?"Name required"}
Arrays
# Define array
FRUITS=("apple" "banana" "cherry")
# Access elements
echo ${FRUITS[0]} # apple
echo ${FRUITS[@]} # all elements
echo ${#FRUITS[@]} # count: 3
# Add element
FRUITS+=("date")
Read User Input
#!/bin/bash
echo "Enter your name:"
read NAME
echo "Hello, $NAME!"
# With prompt
read -p "Enter age: " AGE
echo "You are $AGE years old"
# Silent input (for passwords)
read -sp "Password: " PASS
Environment vs Local Variables
LOCAL_VAR="local" # Only in current shell
export GLOBAL_VAR="global" # Available to child processes
Key Takeaways
- Set variables with
NAME=value(no spaces!) - Access with
$NAMEor${NAME} - Always quote variables:
"$VAR" - Use
$1, $2...for script arguments $(command)captures command output- Use
${#VAR}for string length

