Bash Commands & Scripting
Command Dispatcher Pattern
Create a script that dispatches commands via switch/case:
1#!/bin/bash
2
3# Command dispatcher script
4command_dispatcher() {
5 local cmd="$1"
6 shift # Remove first argument, rest are parameters
7
8 case "$cmd" in
9 start)
10 echo "Starting service..."
11 # Your start logic here
12 ;;
13 stop)
14 echo "Stopping service..."
15 # Your stop logic here
16 ;;
17 restart)
18 stop
19 start
20 ;;
21 status)
22 echo "Checking status..."
23 # Your status logic here
24 ;;
25 deploy)
26 local env="$1"
27 echo "Deploying to $env..."
28 # Your deploy logic here
29 ;;
30 *)
31 echo "Usage: $0 {start|stop|restart|status|deploy <env>}"
32 exit 1
33 ;;
34 esac
35}
36
37# Call dispatcher with all arguments
38command_dispatcher "$@"
Useful Commands
File Operations
1# Find files modified in last 7 days
2find . -type f -mtime -7
3
4# Find and delete files older than 30 days
5find . -type f -mtime +30 -delete
6
7# Find files by size (larger than 100MB)
8find . -type f -size +100M
9
10# Find and replace in files
11find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} +
12
13# Copy with progress
14rsync -ah --progress source/ destination/
15
16# Create directory structure
17mkdir -p path/to/nested/directories
18
19# Disk usage sorted by size
20du -sh * | sort -h
21
22# Find largest files
23find . -type f -exec du -h {} + | sort -rh | head -n 10
Text Processing
1# Extract column from CSV
2cut -d',' -f2 file.csv
3
4# Count lines/words/chars
5wc -l file.txt
6
7# Remove duplicate lines
8sort file.txt | uniq
9
10# Count unique lines
11sort file.txt | uniq -c
12
13# Get lines between patterns
14sed -n '/START/,/END/p' file.txt
15
16# Replace text in-place
17sed -i 's/old/new/g' file.txt
18
19# Print specific lines
20sed -n '10,20p' file.txt
21
22# AWK: sum column
23awk '{sum+=$1} END {print sum}' file.txt
24
25# AWK: print if condition
26awk '$3 > 100' file.txt
27
28# Join lines
29paste -sd',' file.txt
Process Management
1# Find process by name
2ps aux | grep process_name
3
4# Kill process by name
5pkill process_name
6
7# Kill process by port
8lsof -ti:8080 | xargs kill -9
9
10# Run in background
11command &
12
13# Run and detach from terminal
14nohup command &
15
16# Check if process is running
17pgrep -x process_name > /dev/null && echo "Running" || echo "Not running"
18
19# Monitor process
20watch -n 1 'ps aux | grep process_name'
Network Commands
1# Check port is open
2nc -zv hostname 80
3
4# Download file
5curl -O https://example.com/file.zip
6
7# POST JSON data
8curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com
9
10# Check HTTP status
11curl -I https://example.com
12
13# Test DNS
14dig example.com
15
16# Show listening ports
17netstat -tuln
18
19# Show network connections
20ss -tuln
System Information
1# CPU info
2lscpu
3
4# Memory info
5free -h
6
7# Disk space
8df -h
9
10# System uptime
11uptime
12
13# Kernel version
14uname -r
15
16# Distribution info
17cat /etc/os-release
18
19# List loaded modules
20lsmod
21
22# Hardware info
23lshw -short
Scripting Techniques
Error Handling
1#!/bin/bash
2set -euo pipefail # Exit on error, undefined var, pipe failure
3
4# Trap errors
5trap 'echo "Error on line $LINENO"' ERR
6
7# Check command success
8if ! command -v git &> /dev/null; then
9 echo "git not found"
10 exit 1
11fi
Argument Parsing
1#!/bin/bash
2
3# Parse options
4while getopts "hf:v" opt; do
5 case $opt in
6 h)
7 echo "Usage: $0 [-h] [-f file] [-v]"
8 exit 0
9 ;;
10 f)
11 file="$OPTARG"
12 ;;
13 v)
14 verbose=true
15 ;;
16 \?)
17 echo "Invalid option: -$OPTARG" >&2
18 exit 1
19 ;;
20 esac
21done
22
23# Shift past options
24shift $((OPTIND-1))
25
26# Remaining arguments
27echo "Remaining args: $@"
Functions
1#!/bin/bash
2
3# Function with return value
4get_timestamp() {
5 date +%Y%m%d_%H%M%S
6}
7
8# Function with parameters
9backup_file() {
10 local file="$1"
11 local backup_dir="$2"
12
13 if [[ ! -f "$file" ]]; then
14 echo "Error: File not found" >&2
15 return 1
16 fi
17
18 cp "$file" "$backup_dir/$(basename "$file").$(get_timestamp)"
19}
20
21# Usage
22backup_file "/path/to/file.txt" "/backup"
Arrays
1# Declare array
2files=("file1.txt" "file2.txt" "file3.txt")
3
4# Iterate array
5for file in "${files[@]}"; do
6 echo "$file"
7done
8
9# Array length
10echo "${#files[@]}"
11
12# Add to array
13files+=("file4.txt")
14
15# Associative array (dictionary)
16declare -A config
17config[host]="localhost"
18config[port]="8080"
19
20echo "${config[host]}"
String Operations
1# String length
2str="hello"
3echo "${#str}"
4
5# Substring
6echo "${str:0:2}" # "he"
7
8# Replace
9echo "${str/l/L}" # "heLlo"
10
11# Replace all
12echo "${str//l/L}" # "heLLo"
13
14# Remove prefix
15path="/usr/local/bin"
16echo "${path#/usr/}" # "local/bin"
17
18# Remove suffix
19file="document.txt"
20echo "${file%.txt}" # "document"
21
22# Convert to uppercase
23echo "${str^^}"
24
25# Convert to lowercase
26echo "${str,,}"
Conditionals
1# File tests
2if [[ -f "file.txt" ]]; then
3 echo "File exists"
4fi
5
6if [[ -d "directory" ]]; then
7 echo "Directory exists"
8fi
9
10if [[ -x "script.sh" ]]; then
11 echo "File is executable"
12fi
13
14# String tests
15if [[ -z "$var" ]]; then
16 echo "Variable is empty"
17fi
18
19if [[ "$str1" == "$str2" ]]; then
20 echo "Strings match"
21fi
22
23# Numeric tests
24if [[ $num -gt 10 ]]; then
25 echo "Greater than 10"
26fi
27
28# Logical operators
29if [[ -f "file.txt" && -r "file.txt" ]]; then
30 echo "File exists and is readable"
31fi
Loops
1# For loop
2for i in {1..10}; do
3 echo "$i"
4done
5
6# C-style for loop
7for ((i=0; i<10; i++)); do
8 echo "$i"
9done
10
11# While loop
12while read line; do
13 echo "$line"
14done < file.txt
15
16# Until loop
17count=0
18until [[ $count -eq 5 ]]; do
19 echo "$count"
20 ((count++))
21done
Here Documents
1# Multi-line string
2cat << EOF > config.txt
3server {
4 listen 80;
5 server_name example.com;
6}
7EOF
8
9# Here string
10grep "pattern" <<< "string to search"
One-Liners
1# Backup with timestamp
2cp file.txt file.txt.$(date +%Y%m%d_%H%M%S)
3
4# Find and archive
5tar czf archive.tar.gz $(find . -name "*.log")
6
7# Monitor log file
8tail -f /var/log/syslog | grep --line-buffered "ERROR"
9
10# Parallel execution
11cat urls.txt | xargs -P 10 -I {} curl -O {}
12
13# Generate random string
14openssl rand -base64 32
15
16# Check if script is run as root
17[[ $EUID -ne 0 ]] && echo "Must run as root" && exit 1
18
19# Create backup and restore functions
20alias backup='tar czf backup-$(date +%Y%m%d).tar.gz'
21alias restore='tar xzf'
Further Reading
- Bash Reference Manual
- Advanced Bash-Scripting Guide
- ShellCheck - Shell script analysis tool
Related Snippets
- Cisco IOS Commands
Cisco switch and router CLI commands - CMD Commands
Useful Windows Command Prompt commands - PowerShell Commands
Useful PowerShell commands and scripting techniques - Zsh/Sh Commands
Z shell and Bourne shell commands