# Comprehensive Bash & PowerShell Scripting Tutorial

## Introduction

This tutorial provides a complete guide to Bash (Bourne Again SHell) and PowerShell scripting, from basics to advanced topics. Bash is the default shell on most Linux/Unix systems, while PowerShell is Microsoft's powerful scripting environment, now cross-platform.

**Why learn both?**
- Bash: Ubiquitous on servers, great for text processing and Unix tools.
- PowerShell: Object-oriented, excellent for Windows administration, .NET integration, and modern automation.

We'll cover syntax differences, best practices, and practical examples for system programming, utilities, configuration management, and more.

**Prerequisites:** Basic command-line knowledge.

---

## Section 1: Getting Started

### Bash Basics
- Shebang: `#!/bin/bash`
- Make executable: `chmod +x script.sh`
- Run: `./script.sh` or `bash script.sh`

**Hello World:**
```bash
#!/bin/bash
echo "Hello, World!"
```

### PowerShell Basics
- Extension: `.ps1`
- Run: `.\script.ps1` (after setting execution policy if needed: `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser`)

**Hello World:**
```powershell
Write-Output "Hello, World!"
# or simply
"Hello, World!"
```

**Comparison Table:**

| Feature | Bash | PowerShell |
|---------|------|------------|
| Command Style | Commands + options | Cmdlets (Verb-Noun) |
| Output | Text streams | Objects |
| Piping | Text | Objects |

---

## Section 2: Variables and Data Types

### Bash
```bash
name="Grok"  # No spaces around =
echo $name
readonly PI=3.14  # Constant
unset name

# Arrays
fruits=("apple" "banana")
echo ${fruits[0]}
echo ${fruits[@]}

# Associative arrays (Bash 4+)
declare -A colors
colors[red]="#FF0000"
```

### PowerShell
```powershell
$name = "Grok"
$PI = 3.14  # No readonly simple way, use Set-Variable -Option Constant
Remove-Variable name

# Arrays
$fruits = @("apple", "banana")
$fruits[0]

# Hashtables
$colors = @{ Red = "#FF0000" }
$colors.Red
```

**Environment Variables:**
- Bash: `export VAR=value; echo $VAR`
- PS: `$env:VAR = "value"; $env:VAR`

---

## Section 3: Control Structures

### Conditional Statements

**Bash:**
```bash
if [ "$var" -eq 5 ]; then
  echo "Equal"
elif [ "$var" -gt 5 ]; then
  echo "Greater"
else
  echo "Less"
fi

# Case
case $var in
  1) echo "One";;
  *) echo "Default";;
esac
```

**PowerShell:**
```powershell
if ($var -eq 5) {
  Write-Output "Equal"
} elseif ($var -gt 5) {
  Write-Output "Greater"
} else {
  Write-Output "Less"
}

# Switch
switch ($var) {
  1 { "One" }
  default { "Default" }
}
```

### Loops

**Bash For/While:**
```bash
for i in {1..5}; do echo $i; done
for file in *.txt; do echo $file; done

while [ $count -lt 10 ]; do
  ((count++))
done
```

**PowerShell:**
```powershell
for ($i=1; $i -le 5; $i++) { $i }
1..5 | ForEach-Object { $_ }

while ($count -lt 10) { $count++ }
```

---

## Section 4: Functions

**Bash:**
```bash
greet() {
  local name=$1
  echo "Hello, $name!"
}
greet "World"
```

**PowerShell:**
```powershell
function Greet {
  param($name)
  "Hello, $name!"
}
Greet "World"
```

Advanced: Bash uses `return` for exit codes; PS uses `return` for values.

---

## Section 5: Input/Output, Redirection, Pipes

**Bash:**
- Input: `read -p "Enter: " var`
- Redirection: `command > out.txt 2> err.txt`
- Pipe: `ls | grep txt`

**PowerShell:**
- Input: `$var = Read-Host "Enter"`
- Redirection: `command > out.txt 2> err.txt` (similar)
- Pipe: `Get-ChildItem | Where-Object { $_.Name -like "*.txt" }`

**Here Documents (Bash):**
```bash
cat << EOF > file.txt
Content here
EOF
```

---

## Section 6: File and Directory Operations

**Common Commands:**

Bash: `ls, cd, mkdir, rm, cp, mv, find, grep`

PowerShell: `Get-ChildItem (ls), Set-Location (cd), New-Item (mkdir), Remove-Item (rm), Copy-Item, Move-Item, Get-ChildItem -Recurse | Where`

**Example: Backup Script (Bash)**
```bash
#!/bin/bash
tar -czf backup_$(date +%Y%m%d).tar.gz /path/to/dir
```

**PowerShell:**
```powershell
Compress-Archive -Path "dir" -DestinationPath "backup.zip"
```

---

## Section 7: Process Management

**Bash:**
- `ps aux`, `top`, `kill PID`
- Background: `command &`
- Wait: `wait`

**PowerShell:**
- `Get-Process`, `Stop-Process`
- `Start-Process`, `Wait-Process`

**Systemd/Services (Linux Bash):**
```bash
systemctl status service
```

**Windows Services (PS):**
```powershell
Get-Service | Start-Service
```

---

## Section 8: Networking and System Utilities

**Bash:**
- `curl, wget, ping, ssh, scp, netstat/ss`
- `ifconfig/ip addr`

**PowerShell:**
- `Invoke-WebRequest`, `Test-NetConnection`, `Enter-PSSession`
- Remoting: `Invoke-Command -ComputerName remote`

**Example: Check Website (Bash)**
```bash
curl -I https://example.com
```

---

## Section 9: Error Handling and Debugging

**Bash:**
- `set -euo pipefail` for strict mode
- `trap 'echo Error' ERR`
- Debug: `bash -x script.sh`

**PowerShell:**
- `Try { } Catch { }`
- `$ErrorActionPreference = "Stop"`
- Debug: `Set-PSDebug -Trace 1`

---

## Section 10: Text Processing - Regex, sed, awk

**Bash Tools:**
- `grep -E 'pattern'`
- `sed 's/old/new/g'`
- `awk '{print $1}'`

**PowerShell:**
- `-match`, `-replace`
- `Select-String`
- Custom with .NET regex

---

## Section 11: Advanced Bash Topics

- **Arrays & Indirect References**
- **Subshells & Process Substitution**
- **/proc and /dev**
- **Coproc, Job Control**
- **Traps and Signals**

See Advanced Bash-Scripting Guide for depth.include render_inline_citation with citation_id is 36

---

## Section 12: Advanced PowerShell Topics

- **Modules:** `Import-Module`
- **Classes & OOP**
- **Desired State Configuration (DSC)**
- **Remoting & Workflows**
- **.NET Integration:** `[System.IO.File]::WriteAllText()`

**Custom Cmdlet-like Functions**

---

## Section 13: System Programming & Automation

**Bash System Scripts:**
- User management: `useradd, usermod`
- Package management: `apt/yum/dnf`
- Monitoring: `df, free, vmstat`

**PowerShell:**
- Active Directory: `Get-ADUser` (after RSAT)
- WMI/CIM: `Get-CimInstance`
- Event Logs: `Get-EventLog`

**Cross-platform:** Use PowerShell Core (pwsh) on Linux.

---

## Section 14: Utilities and Compilers

**Building with Compilers (Bash):**
```bash
gcc -o program source.c
./program
# Script to build:
if [ -f Makefile ]; then make; else gcc ...; fi
```

**PowerShell with C#:**
```powershell
Add-Type @"
public class Hello {
  public static void Main() { System.Console.WriteLine("Hi"); }
}
"@
[Hello]::Main()
```

**Script Utilities:**
- Log rotation, backups, monitoring dashboards.

---

## Section 15: Configuration Files

**INI Parsing**

**Bash:**
```bash
# Simple
while IFS='=' read -r key value; do
  eval "$key=\"$value\""
done < config.ini
```

**PowerShell:**
```powershell
Get-Content config.ini | ConvertFrom-StringData
```

**JSON/YAML:**

**Bash:** Use `jq` for JSON.
```bash
value=$(jq -r '.key' config.json)
```

**PowerShell:**
```powershell
$json = Get-Content config.json | ConvertFrom-Json
$json.key
# YAML: Install module or use ConvertFrom-Yaml
```

**Best Practices:** Use dedicated parsers, validate inputs.include render_inline_citation with citation_id is 16

---

## Section 16: Best Practices & Security

- **Quoting:** Always quote variables: `"$var"`
- **Bash:** Use `[[ ]]` over `[ ]`
- **PS:** Use approved verbs, parameter validation
- **Security:** Avoid `eval`, sanitize inputs, least privilege
- **Style:** Consistent indentation, comments, functions over monolithic scripts
- **Version Control:** Git for scripts
- **Testing:** Unit tests with `bats` (Bash) or Pester (PS)

**Pitfalls:**
- Bash word splitting, globbing
- PowerShell execution policy

---

## Section 17: Practical Projects & Examples

1. **Backup Script** - Cross-platform file backup with logging.
2. **System Monitor** - CPU, memory alerts.
3. **Deployment Script** - Build, test, deploy app.
4. **Config Manager** - Parse and apply settings.
5. **Network Scanner** - Ping sweep or port check.

**Full Example: Multi-OS Info Script**

**Bash:**
```bash
#!/bin/bash
echo "Hostname: $(hostname)"
echo "OS: $(uname -s)"
df -h
```

**PowerShell:**
```powershell
"Hostname: $env:COMPUTERNAME"
Get-ComputerInfo
```

---

## Section 18: Resources & Further Reading

- Bash: Advanced Bash-Scripting Guide, Greg's Wiki
- PowerShell: Microsoft Learn, "Mastering PowerShell Scripting"
- Practice: Write daily automation scripts.
- Tools: ShellCheck for Bash, PSScriptAnalyzer for PS.

**Conclusion:** Practice by automating your workflow. Start small, iterate.

This tutorial is a starting point—experiment and build! 

*Generated as a comprehensive reference. Expand with hands-on coding.*
