Bash Introduction

Bash (Bourne Again SHell) is the default command-line shell on most Linux and macOS systems. It's a powerful scripting language for automating tasks, managing files, and controlling system operations.

Why Learn Bash?

  • Automation — Script repetitive tasks instead of doing them manually
  • System administration — Manage servers, processes, and files
  • DevOps — CI/CD pipelines, Docker, cloud deployment
  • Data processing — Parse logs, transform text, analyze data
  • Every Linux server has Bash — it's the universal tool

Your First Script

Bash
#!/bin/bash
# hello.sh — my first Bash script

echo "Hello, World!"
echo "Today is $(date)"
echo "You are $(whoami)"
Bash
# Make it executable and run it
chmod +x hello.sh
./hello.sh

Variables

Bash
# Assign (NO spaces around =)
name="Alice"
age=30
readonly PI=3.14159    # Constant

# Use variables
echo "Name: $name"
echo "Age: ${age}"
echo "Path: $HOME"
echo "User: $(whoami)"

# String operations
str="Hello, World!"
echo ${#str}              # Length: 13
echo ${str:0:5}           # Substring: Hello
echo ${str/World/Bash}    # Replace: Hello, Bash!

# Command substitution
files=$(ls -la)
current_date=$(date +%Y-%m-%d)

Special Variables

Bash
$0    # Script name
$1-$9 # Arguments (positional parameters)
$#    # Number of arguments
$@    # All arguments (as separate words)
$*    # All arguments (as a single string)
$?    # Exit code of last command
$$    # Process ID of script
$!    # PID of last background process

Arithmetic

Bash
a=10
b=3

echo $((a + b))    # 13
echo $((a - b))    # 7
echo $((a * b))    # 30
echo $((a / b))    # 3
echo $((a % b))    # 1
echo $((a ** 2))   # 100

# Floating point (use bc)
result=$(echo "scale=2; 10 / 3" | bc)
echo $result  # 3.33

Arrays

Bash
# Indexed arrays
fruits=("apple" "banana" "cherry")
echo ${fruits[0]}        # apple
echo ${fruits[@]}        # all elements
echo ${#fruits[@]}       # 3 (length)

fruits+=("date")         # Append
unset fruits[1]          # Remove element

# Associative arrays
declare -A scores
scores[alice]=95
scores[bob]=87
echo ${scores[alice]}    # 95
echo ${!scores[@]}       # alice bob (all keys)

💡 Tip: Use "$variable" (with quotes) to prevent word splitting. Unquoted $var can break on spaces and special characters.

Next: Commands and Pipes

Knowledge Check

4 questions — test your understanding

1

What does `set -e` do at the top of a Bash script?

2

What is the difference between `>` and `>>` in Bash?

3

What does `$?` contain after a command runs?

4

What does `$#` represent in a Bash script?