ShBash · Lesson 2 of 8

Variables & Input

Bash variables have no types. Everything is a string. This is either simple or chaos, depending on what you're trying to do with numbers.

Bash
#!/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: $$"
Bash
#!/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!"
⚠ Warning
Always quote your variables: use "$name" not $name. Unquoted variables are subject to word splitting and glob expansion, which causes subtle, hard-to-debug bugs when values contain spaces or special characters.