# #12 Shell Scripting

# 🐚 **Shell Scripting in Linux — Automating Your Everyday Tasks Like a Pro**

> “If you ever find yourself doing the same task twice on Linux — automate it.” 💡

Shell scripting is one of the most powerful skills any Linux user, DevOps engineer, or cloud professional can master.  
Whether your Linux environment is on **AWS EC2**, **Docker**, or your **MacBook terminal**, shell scripting helps you **automate daily tasks** — from system checks to deployments.

---

## ⚙️ **What is Shell Scripting?**

**Shell Scripting** is the process of **automating repetitive tasks** by writing a sequence of Linux commands in a file.  
This script is then executed by the shell — typically **bash**, **sh**, **dash**, or **ksh** — depending on your system.

You can automate things like:

* System health checks (CPU, memory, disk)
    
* File backups
    
* Application deployments
    
* Monitoring and reporting tasks
    

---

## 📝 **Step 1: Create Your First Shell Script**

Use the `touch` command to create a new file:

```xml
touch first-shell-script.sh
```

Check if your file exists:

```xml
ls -ltr
```

### 📘 Understanding `ls -ltr`

* `l` → long format (detailed info)
    
* `t` → sort by modification time
    
* `r` → reverse order (latest last)
    

Output columns include:

* **File permissions**
    
* **Owner and group**
    
* **File size**
    
* **Last modified date**
    
* **File name**
    

You can even check command manuals with:

```xml
man ls
```

🧠 *Tip:* The `man` (manual) command gives detailed documentation for any Linux command.

---

## ✍️ **Step 2: Open and Write the Script**

Use **vi** (pre-installed) or **vim** (needs installation):

```xml
vi first-shell-script.sh
```

Once inside:

* Press `i` to enter **Insert Mode**
    
* Type your script (start simple!)
    
* Press `Esc` → type `:wq!` → hit Enter to save & exit  
    *(Use* `:q!` to exit without saving)
    

---

## 💡 **Step 3: The Shebang (#!) — The First Line of Every Script**

The **shebang** (`#!`) tells Linux which interpreter should execute the script.

```xml
#!/bin/bash
```

### Common Shebang Options:

| Interpreter | Path | Use |
| --- | --- | --- |
| Bash | `/bin/bash` | Default shell |
| Dash | `/bin/dash` | Lightweight system shell |
| Sh | `/bin/sh` | POSIX standard shell |
| Ksh | `/bin/ksh` | Korn shell (used in legacy systems) |

🧠 **Why it matters:**  
Different Linux systems might use different default shells — writing the correct shebang ensures your script runs everywhere.

---

## 🧾 **Step 4: Write Your First Script**

Inside your file:

```xml
#!/bin/bash

echo "My name is Piyush"
```

Save and exit (`:wq!`).

To check the contents:

```xml
cat first-shell-script.sh
```

---

## 🔓 **Step 5: Make the Script Executable**

```xml
chmod 755 first-shell-script.sh
```

### Breakdown:

| Permission | Value | Meaning |
| --- | --- | --- |
| r (read) | 4 | View contents |
| w (write) | 2 | Modify contents |
| x (execute) | 1 | Run as a program |

Example:

* `chmod 777` → full permissions for all users
    
* `chmod 700` → only owner can access
    

---

## 🚀 **Step 6: Run Your Script**

You can execute it in two ways:

```xml
sh first-shell-script.sh
```

or

```xml
./first-shell-script.sh
```

Output:

```xml
My name is Piyush
```

---

## 🪄 **Step 7: Add System Commands**

Let’s make it useful!

```xml
#!/bin/bash
set -x  # Enable debug mode

echo "Checking system health..."

echo "Disk Usage:"
df -h

echo "Memory Info:"
free -g

echo "CPU Count:"
nproc

echo "Process List:"
ps -ef | grep "amazon"
```

### Explanation:

* `set -x` → enables **debug mode**, showing each command as it runs
    
* `df -h` → shows **disk space**
    
* `free -g` → shows **memory usage in GB**
    
* `nproc` → shows **CPU cores**
    
* `ps -ef` → lists all processes
    
* `grep` → filters specific results
    
* `|` (pipe) → sends the output of one command as input to another
    

🧠 *Example:*  
`ps -ef | grep "nginx"` → shows all Nginx-related processes.

---

## 🧩 **Understanding Piping & Data Streams**

Linux uses **data channels**:

* **stdin (0)** → input
    
* **stdout (1)** → output
    
* **stderr (2)** → errors
    

When you use a **pipe (**`|`), the **stdout** of the first command becomes the **stdin** of the next.

Example:

```xml
date | grep 2025
```

Here, the `date` command sends its output to `grep`, which filters it.

---

## 📚 **Step 8: Using Comments**

Start lines with `#` to add comments — ignored during execution.

```xml
#!/bin/bash
# Author: Piyush
# Purpose: Demonstrate shell scripting basics
```

> 🧠 Comment everything — it’s your best friend when debugging!

---

## 🗂️ **Bonus Commands Recap**

| Command | Purpose |
| --- | --- |
| `mkdir` | Make a directory |
| `cd` | Change directory |
| `history` | Show previous commands |
| `rm -rf` | Delete file/folder (use carefully!) |
| `cat` | Display file content |
| `chmod` | Change file permissions |
| `ps -ef` | Show process details |
| `grep` | Filter text |
| \` | \` |

---

## 🧠 **Key Learnings Recap**

✅ How to create and edit shell scripts  
✅ Understanding of **Shebang** and **file permissions**  
✅ Difference between `vi`, `vim`, `cat`, and `chmod`  
✅ Use of **debug mode**, **piping**, and **grep**  
✅ Executing system commands in a script

---

## ⚡ **Final Thoughts**

Shell scripting is where **Linux automation truly begins**. Once you master this, you can:

* Automate AWS EC2 health checks
    
* Write startup scripts for Docker containers
    
* Schedule CRON jobs
    
* Even create **DevOps automation pipelines**
    

> “Every powerful Linux system hides behind a simple `.sh` file.”

---

### 🔗 Continue Learning:

* 📘 Next Post: **“Understanding CRON Jobs — Scheduling Automation in Linux”**
    
* 🧠 Previous: **“Understanding Linux Folder Structure and File Permissions”**
    

Follow my journey on Hashnode  
💼 Connect on [LinkedIn](https://linkedin.com/) — sharing daily learnings on Linux, DevOps & Cloud.
