Lesson 2 of 8
Variables & Input
Learn how to store values in , do arithmetic and read input. In every variable is a , so arithmetic needs its own syntax.
#!/bin/bash
# Variable assignment — NO spaces around =
name="Alice"
age=30
greeting="Hello"
# Access with $
echo "$name"
echo "Name: $name, Age: $age"
echo "${name}'s age is ${age}" # {} braces for clarity
# Command substitution
current_date=$(date +%Y-%m-%d)
file_count=$(ls | wc -l)
echo "Date: $current_date, Files: $file_count"
# Arithmetic — must use $(( ))
a=10
b=3
echo $((a + b)) # 13
echo $((a - b)) # 7
echo $((a * b)) # 30
echo $((a / b)) # 3 (integer division!)
echo $((a % b)) # 1
# Increment/decrement
count=0
((count++))
((count += 5))
echo $count # 6
# Special variables
echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"
echo "Last exit code: $?"
echo "Current PID: $$"#!/bin/bash
# Reading user input
echo -n "Enter your name: "
read name
echo "Hello, $name!"
# Read with a prompt
read -p "Enter your age: " age
echo "In 10 years you'll be $((age + 10))"
# Silent input (for passwords)
read -sp "Enter password: " password
echo "" # newline after silent input
echo "Password length: ${#password}"
# Read with timeout
if read -t 5 -p "Quick! Type something (5s): " input; then
echo "You typed: $input"
else
echo "Too slow!"
fi
# Read into array
read -a words <<< "apple banana cherry"
echo "First: ${words[0]}"
echo "All: ${words[@]}"
# Command-line arguments
if [ $# -lt 2 ]; then
echo "Usage: $0 <first-name> <last-name>"
exit 1
fi
echo "Hello, $1 $2!"Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.