One_liners
Chapter 34: Common Bash One-liners
Section titled “Chapter 34: Common Bash One-liners”Overview
Section titled “Overview”This chapter covers essential bash one-liners that every DevOps engineer should know. These commands are invaluable for system administration, log analysis, and automation.
File Operations
Section titled “File Operations”Basic File Operations
Section titled “Basic File Operations”# Count lines in filewc -l file.txt
# Count words in filewc -w file.txt
# Count characterswc -c file.txt
# Get file size in human-readable formatls -lh file.txt
# Find largest files in directoryls -lS | head -10
# Find files modified in last N daysfind /path -mtime -N
# Find files larger than N MBfind /path -size +NM
# Remove empty files/directoriesfind /path -type f -empty -deleteText Processing
Section titled “Text Processing”grep and Search
Section titled “grep and Search”# Search in filesgrep -r "pattern" /path
# Case-insensitive searchgrep -ri "pattern" /path
# Show line numbersgrep -n "pattern" file.txt
# Show context (before, after, around)grep -B3 -A3 "pattern" file.txt
# Count matchesgrep -c "pattern" file.txt
# Show only matching partgrep -o "pattern" file.txt
# Use regexgrep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" file.txtsed One-liners
Section titled “sed One-liners”# Replace textsed -i 's/old/new/g' file.txt
# Delete lines containing patternsed -i '/pattern/d' file.txt
# Insert line before patternsed -i '/pattern/i\New line' file.txt
# Print specific linessed -n '5p' file.txtsed -n '5,10p' file.txt
# Remove trailing whitespacesed -i 's/[[:space:]]*$//' file.txtawk One-liners
Section titled “awk One-liners”# Print specific columnawk '{print $1}' file.txt
# Print multiple columnsawk '{print $1, $3}' file.txt
# Print last columnawk '{print $NF}' file.txt
# Sum columnawk '{sum+=$1} END {print sum}' file.txt
# Filter by conditionawk '$3 > 100' file.txt
# Print with formatawk '{printf "%-10s %5d\n", $1, $2}' file.txtSystem Information
Section titled “System Information”Hardware and OS
Section titled “Hardware and OS”# Show system informationuname -a
# Show kernel versionuname -r
# Show CPU infolscpu
# Show memory infofree -h
# Show disk usagedf -h
# Show disk usage of current directorydu -sh .
# Show disk usage of subdirectoriesdu -h --max-depth=1Process Management
Section titled “Process Management”# Show processesps aux
# Show processes by namepgrep -a process_name
# Kill process by namepkill process_name
# Kill process by IDkill $(pgrep process_name)
# Show top processes by memoryps aux --sort=-%mem | head -10
# Show top processes by CPUps aux --sort=-%cpu | head -10Network Operations
Section titled “Network Operations”Network Diagnostics
Section titled “Network Diagnostics”# Show IP addressip addr show
# Show routing tableip route
# Test connectivityping -c 4 google.com
# Check open portsss -tulpn
# Show network connectionsnetstat -ant
# DNS lookupdig example.com
# Check port connectivitync -zv host portLog Analysis
Section titled “Log Analysis”Common Log Patterns
Section titled “Common Log Patterns”# Count HTTP status codesawk '{print $9}' access.log | sort | uniq -c | sort -rn
# Find 5xx errorsgrep " 5[0-9][0-9] " access.log
# Find specific IPgrep "192.168.1.100" access.log
# Extract timestampsawk '{print $4, $5}' access.log
# Count unique IPsawk '{print $1}' access.log | sort -u | wc -l
# Show most visited URLsawk '{print $7}' access.log | sort | uniq -c | sort -rn | head -10Package Management (Arch Linux)
Section titled “Package Management (Arch Linux)”pacman Commands
Section titled “pacman Commands”# Sync databasessudo pacman -Sy
# Upgrade systemsudo pacman -Syu
# Install packagesudo pacman -S package_name
# Remove packagesudo pacman -R package_name
# Remove with dependenciessudo pacman -Rns package_name
# Search for packagepacman -Ss search_term
# List installed packagespacman -Q
# List orphan packagespacman -QdtAUR Helpers
Section titled “AUR Helpers”# Using yayyay -S package_nameyay -R package_nameyay -Ss search_term
# Using paruparu -S package_nameDocker Commands
Section titled “Docker Commands”Common Docker Operations
Section titled “Common Docker Operations”# List containersdocker ps -a
# List imagesdocker images
# Remove stopped containersdocker container prune -f
# Remove unused imagesdocker image prune -f
# Remove unused volumesdocker volume prune -f
# Show container logsdocker logs -f container_name
# Show container statsdocker stats --no-stream
# Execute command in containerdocker exec -it container_name /bin/bashGit Commands
Section titled “Git Commands”Common Git Operations
Section titled “Common Git Operations”# Show recent commitsgit log --oneline -10
# Show changed filesgit diff --name-only
# Show branchgit branch
# Show remotegit remote -v
# Show statusgit status
# Add all changesgit add -A
# Create branchgit checkout -b branch_nameText Manipulation
Section titled “Text Manipulation”Useful One-liners
Section titled “Useful One-liners”# Sort and get uniquesort file.txt | uniq
# Count unique linessort -u file.txt | wc -l
# Reverse linestac file.txt
# Randomize linesshuf file.txt
# Extract column from CSVcut -d',' -f1 file.csv
# Merge two filespaste file1.txt file2.txt
# Split file into chunkssplit -l 1000 file.txt chunk_
# Convert to uppercasetr '[:lower:]' '[:upper:]' < file.txt
# Remove duplicate linesawk '!seen[$0]++' file.txtDate and Time
Section titled “Date and Time”Date Operations
Section titled “Date Operations”# Current datedate "+%Y-%m-%d"
# Current timedate "+%H:%M:%S"
# Current timestampdate +%s
# Date from timestampdate -d @timestamp
# Yesterdaydate -d "yesterday"
# Tomorrowdate -d "tomorrow"
# Add daysdate -d "+7 days"
# Format for filenamesdate +%Y%m%d_%H%M%SVariables and Arrays
Section titled “Variables and Arrays”Variable Manipulation
Section titled “Variable Manipulation”# Get string length${#variable}
# Extract substring${variable:position:length}
# Replace pattern${variable//old/new}
# Remove pattern${variable#pattern}${variable##pattern}Loop Examples
Section titled “Loop Examples”For Loops
Section titled “For Loops”# Loop through filesfor f in *.txt; do echo "$f"; done
# Loop through numbersfor i in {1..10}; do echo "$i"; done
# Loop through arrayfor item in "${array[@]}"; do echo "$item"; done
# Loop through command outputfor line in $(command); do echo "$line"; doneSummary
Section titled “Summary”In this chapter, you learned:
- ✅ File operation one-liners
- ✅ Text processing (grep, sed, awk)
- ✅ System information commands
- ✅ Process management
- ✅ Network operations
- ✅ Log analysis
- ✅ Package management (Arch Linux)
- ✅ Docker commands
- ✅ Git commands
- ✅ Text manipulation
- ✅ Date and time operations
- ✅ Variable manipulation
- ✅ Loop examples
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about Code Style and Organization.
Previous Chapter: Best Practices Next Chapter: Code Style and Organization