# Bash Scripting for Beginners: Learn the Basics Step by Step

> Author: [Oussama Ghaieb](https://oussama.ghaieb.com/about-me)
> Canonical: https://oussama.ghaieb.com/posts/bash-scripting-for-beginners-learn-the-basics-step-by-step

# <span class="hover:bg-yellow-100">Bash Scripting for Beginners: Learn the Basics Step by Step</span>

Bash scripting is one of the most powerful skills you can learn as a developer, DevOps engineer, or system administrator. With just a few lines of code, you can:  

✅ **Automate repetitive tasks** (e.g., backups, log cleaning)  
✅ **Manage systems efficiently** (e.g., bulk user creation)  
✅ **Build small command-line tools** (e.g., file renamers, log parsers)  

In this guide, you’ll learn **Bash scripting from scratch**—no prior experience needed. We’ll cover core concepts with **copy-paste examples** you can modify and use immediately.  

---

## 📄 What Is a Bash Script?  

A Bash script is a **plain text file** containing commands that run in sequence—just like typing them in the terminal.  

### 🔹 How to Create & Run a Script  

1. **Write commands in a file** (e.g., `hello.sh`):  
   ```bash
   #!/bin/bash  # This is called the "shebang"—it tells the system to use Bash.
   echo "Hello, World!"
   ```  

2. **Make it executable**:  
   ```bash
   chmod +x hello.sh  # Grants execute permission.
   ```  

3. **Run it**:  
   ```bash
   ./hello.sh  # Output: "Hello, World!"
   ```  

---

## 🔤 Bash Syntax Basics  

### ✅ 1. **Comments**  
Use `#` for single-line comments. Bash ignores text after `#`.  
```bash
# This line is a comment.  
echo "This runs."  # This part is also ignored.
```  

---

### ✅ 2. **Variables**  
Store text, numbers, or command outputs. **No spaces around `=`!**  
```bash
name="Oussama"  
echo "Hello, $name!"  # Output: "Hello, Oussama!"  
```  

🔹 **Best Practices**:  
- Quote variables to avoid errors with spaces:  
  ```bash
  full_name="Oussama Ghaieb"  
  echo "Hello, $full_name"  # Works!  
  ```  
- Use curly braces for clarity: `${variable}`.  

---

### ✅ 3. **User Input**  
Use `read` to prompt for input:  
```bash
read -p "Enter your age: " age  
echo "You are $age years old."  
```  

---

### ✅ 4. **Conditionals (`if` Statements)**  
Compare values and act accordingly:  
```bash
if [ "$age" -ge 18 ]; then  # -ge = "greater or equal"  
  echo "You are an adult."  
else  
  echo "You are a minor."  
fi  
```  

🔹 **Key Rules**:  
- `=` for strings, `-eq`/`-lt`/`-gt` for numbers.  
- Always put spaces inside `[ ]`.  

---

### ✅ 5. **Loops**  

#### 🔄 **`for` Loop**  
Iterate over a list:  
```bash
for fruit in "apple" "banana" "cherry"; do  
  echo "Fruit: $fruit"  
done  
```  

#### 🔁 **`while` Loop**  
Run while a condition is true:  
```bash
count=1  
while [ $count -le 3 ]; do  
  echo "Count: $count"  
  ((count++))  # Increment count  
done  
```  

---

### ✅ 6. **Functions**  
Group reusable code:  
```bash
greet() {  
  echo "Hello, $1!"  
}  

greet "Oussama"  # Output: "Hello, Oussama!"  
```  

🔹 **Return Values**:  
Bash functions return exit codes. Use `echo` to "return" data:  
```bash
add() {  
  echo $(($1 + $2))  
}  

result=$(add 5 7)  # Captures output  
echo "Sum: $result"  # Output: "Sum: 12"  
```  

---

### ✅ 7. **Arrays**  
Store multiple values:  
```bash
fruits=("apple" "banana" "cherry")  
echo "First fruit: ${fruits[0]}"  # Output: "apple"  
```  

Loop through an array:  
```bash
for fruit in "${fruits[@]}"; do  
  echo "$fruit"  
done  
```  

---

### ✅ 8. **Exit Codes**  
`0` = success, `1-255` = error. Check command success:  
```bash
if ! command -v git &> /dev/null; then  
  echo "Error: Git is not installed."  
  exit 1  
fi  
```  

---

### ✅ 9. **Command Substitution**  
Run a command and store its output:  
```bash
current_date=$(date)  
echo "Today is $current_date"  
```  

---

## 🧪 **Practical Example: Automated Backup Script**  
```bash
#!/bin/bash  

# Create a backup directory with today's date  
backup_dir="/tmp/backup_$(date +%Y%m%d)"  
mkdir -p "$backup_dir"  

# Copy important files  
cp -r ~/documents "$backup_dir"  

echo "Backup saved to: $backup_dir"  
```  

**Run it**:  
```bash
chmod +x backup.sh  
./backup.sh  
```  

---

## 🎓 **Pro Tips for Bash Scripting**  
1. **Debug with `bash -x script.sh`** (prints each command before running).  
2. **Use `set -e`** to exit on errors.  
3. **Always quote variables** (`"$var"`) to avoid word splitting.  
4. **Check for dependencies** at script start (e.g., `curl`, `git`).  

---

## 🚀 **What’s Next?**  
- Learn **`awk`** and **`sed`** for text processing.  
- Explore **cron jobs** to schedule scripts.  
- Try writing a **log analyzer** or **file organizer**.  

Bash is preinstalled on Linux/macOS, and mastering it unlocks **unlimited automation power**. Start small, experiment often, and happy scripting! 🐧
