DevOps Linux Commands: Complete Guide with Practical Use Cases
Part 1: File Ownership and Permissions
chown - Change File Owner
Commands: chown new_name file | chown new_name:new_grp file
DevOps Use Cases:
Application Deployment Pipeline
Copy chown ubuntu:webapp /opt/application/config.yml After deploying an application artifact, you need to ensure the web application user owns the config files. This prevents permission errors when the application process tries to read configuration.
Docker Container Access Control
Copy chown -R appuser:appgroup /home/appuser/workspace When mounting volumes into containers, change ownership recursively so the containerized process can access files without permission denied errors.
Backup Restore Operations
Copy chown ubuntu:ubuntu /home/ubuntu/restored_backup/ After restoring files from backup, reassign ownership to ensure the correct user can access them. This is critical in disaster recovery scenarios.
Multi-tenant Infrastructure
Copy chown customer1:tenant1_group /var/www/customer1/
chown customer2:tenant2_group /var/www/customer2/ In a multi-tenant Kubernetes setup, assign file ownership per tenant to maintain isolation and security boundaries.
Part 2: Text Processing - sed (Stream Editor)
sed - On-the-fly Text Replacement
Basic Syntax: sed 's/old_pattern/new_pattern/g' filename
Global Replacement: sed 's/old_pattern/new_pattern/g'
Command: sed 's/samsung/sony/g' newfile
DevOps Use Cases:
Configuration Templating in CI/CD
Before deploying to production, replace environment-specific values in config files without manual editing.
Log Sanitization
Remove sensitive data from logs before shipping them to centralized logging (ELK Stack, Splunk).
Batch Configuration Updates
Update database connection strings across multiple environment config files in one operation.
In-Place Editing: sed -i
Command: sed -i 's/Testing/development/g' file2
DevOps Use Cases:
Infrastructure as Code (IaC) Updates
Update Terraform files in-place to scale up instance types across environments.
Kubernetes Manifest Updates
Update container image versions in Kubernetes manifests before applying with kubectl apply.
Jenkins Pipeline Configuration
Update environment variables in-place during CI/CD pipeline execution.
Case-Insensitive Replacement: sed 's/pattern/replacement/gi'
Command: sed 's/testing/development/gi' file2
DevOps Use Cases:
Application Log Filtering (Case-Insensitive)
Normalize error messages regardless of case in application logs for consistent monitoring alerts.
Replacement on Specific Line: sed '2s/pattern/replacement/gi'
Command: sed '2s/testing/development/gi' file2
DevOps Use Cases:
Surgical Config File Updates
Update only the 3rd line where the debug flag is set, avoiding unintended changes elsewhere.
Kubernetes Service Port Updates
Change a specific service port definition on line 5 without touching other configurations.
Range-Based Replacement: sed '10,30s/pattern/replacement/gi'
Command: sed '10,30s/testing/development/gi' file2
DevOps Use Cases:
Large Configuration Files
Update domain references only in the server block (lines 50-100) of a large Nginx config file.
Log File Analysis
Update severity levels only for a specific section of logs during a troubleshooting window.
From Line to End: sed '30,$s/pattern/replacement/gi'
Command: sed '30,$s/testing/development/gi' file2
DevOps Use Cases:
Configuration Migration
Update all database references from line 20 onwards in a configuration file during infrastructure migration.
Print Specific Line: sed -n '98p'
Commands: sed -n '98p' file | sed -n '2p' file2
DevOps Use Cases:
Extract Build Information
Extract version information from a specific line in build logs for versioning purposes.
Kubernetes Event Extraction
Extract a specific line from pod events for debugging.
Print Line Range: sed -n '10,20p'
Command: sed -n '10,20p' file
DevOps Use Cases:
Log Excerpt Extraction
Extract 50 lines of context around an error timestamp for detailed analysis.
Terraform Plan Analysis
Review only the resource changes section of Terraform plan output.
Delete Specific Line: sed '2d'
Command: sed '2d' file2
DevOps Use Cases:
Remove Configuration Comments
Remove a deprecated configuration line that breaks newer application versions.
Clean Kubernetes Manifest
Remove a specific annotation or label from a Kubernetes manifest.
Delete Line Number: sed '100d'
Command: sed '100d' file
DevOps Use Cases:
Fix Malformed Config
Remove a problematic line from config file and apply directly to Kubernetes.
Part 3: Column Extraction - cut
Extract Single Column: cut -d " " -f1
Commands: cut -d " " -f1 filename | cut -d " " -f3 filename
DevOps Use Cases:
Extract IPs from Server List
Extract usernames running Java processes for audit purposes.
Parse AWS EC2 Instance IDs
Extract instance IDs for batch operations.
Multiple Columns: cut -d " " -f1,2
Command: cut -d " " -f1,2 filename
DevOps Use Cases:
Extract User and PID from Process List
Extract username and PID pairs for process killing scripts in automation.
Parse HTTP Access Logs
Extract IP addresses and HTTP status codes for traffic analysis.
Part 4: Advanced Text Processing - awk
Print Specific Field: awk -F " " '{print $2}'
Commands: awk -F " " '{print $2}' test1 | awk -F " " '{print $3}' test1
DevOps Use Cases:
Extract Memory Usage from top
Extract memory percentage for monitoring and alerting in Prometheus exporter scripts.
Parse Kubernetes Pod Resources
Extract CPU usage per pod for capacity planning.
Last Field: awk -F " " '{print $NF}'
Command: awk -F " " '{print $NF}' test1
DevOps Use Cases:
Extract Process Names
Count frequency of running processes for anomaly detection.
Get Domain from URLs in Logs
Identify most requested domains from web server logs.
Second-to-Last Field: awk -F " " '{print $(NF-1)}'
Command: awk -F " " '{print $(NF-1)}' test1
DevOps Use Cases:
Extract HTTP Status Codes
Extract HTTP status from curl verbose output for health checks.
Multiple Field Output: awk -F " " '{print $1,$3}'
Command: awk -F " " '{print $1,$3}' test1
DevOps Use Cases:
Extract Critical Log Data
Extract timestamp and error code for incident tracking.
Kubernetes Event Parsing
Extract namespace and event reason for cluster monitoring.
Part 5: Process Management
List All Processes: ps -ef
Command: ps -ef
DevOps Use Cases:
Container Health Check Script
Monitor critical application processes and restart if they crash.
Find Specific Process: ps -ef|grep -i "process_name"
Command: ps -ef|grep -i "process_name/service_name"
DevOps Use Cases:
CI/CD Pipeline Dependency Check
Verify Docker daemon is running before starting CI/CD jobs.
Load Balancer Health Verification
Check if Nginx is running for load balancer verification in health checks.
Multiple Process Grep: ps -ef|grep -ie "process1" -ie "process2"
Command: ps -ef|grep -ie "process1" -ie "process2"
DevOps Use Cases:
Multi-Service Monitoring
Check if all required application services are running in a microservices environment.
Kill Process: kill -9 "pid"
Command: kill -9 "pid"
DevOps Use Cases:
Force Kill Hung Deployment Process
Force terminate a stuck deployment to allow new deployment to proceed.
Cleanup on Container Exit
Clean up zombie processes after container termination.
Service Control Commands
Commands:
service service_name stop
service service_name start
service service_name restart
DevOps Use Cases:
Blue-Green Deployment
Stop old application, deploy new version, and start service.
Zero-Downtime Database Migration
Coordinate service downtime with migration windows.
Process by User: ps -u "user_name"
Commands: ps -u "user_name" | ps -u "ubuntu"
DevOps Use Cases:
Identify Resource-Heavy Users
Find top 5 memory-consuming processes for a specific user in performance troubleshooting.
Container User Process Tracking
Count total processes running under application user for capacity monitoring.
Add New User: adduser username
Command: adduser username
DevOps Use Cases:
Automation User Creation
Create dedicated user for CI/CD pipeline with required group memberships.
Multi-Tenant Isolation
Create isolated users for different customers in SaaS platforms.
Part 6: File Search - find
Basic File/Directory Search: find . -iname "test"
Commands:
find . -iname "test" (case-insensitive)
find /Users/hareeshab/Documents -iname "dir2"
DevOps Use Cases:
Locate Configuration Files
Find configuration files for backup and version control in multi-server environments.
Docker Volume Cleanup
Find and audit unused Docker volumes for cleanup.
Find by Type - Files: find . -type f -iname "test"
Command: find . -type f -iname "test"
DevOps Use Cases:
Locate Application Logs
Find error logs modified in last 24 hours for incident investigation.
Find by Type - Directories: find . -type d -iname "test"
Command: find . -type d -iname "test"
DevOps Use Cases:
Kubernetes Secret Volume Mounts
Locate secret directories in container filesystem for security audits.
Find by Modification Time (Days): find . -type f -mtime -10
Commands:
find . -type f -mtime -10 (modified within 10 days)
find . -type d -mtime -10
find . -type d -mtime +5 (modified more than 5 days ago)
find . -type f -mtime +20
DevOps Use Cases:
Log Rotation Automation
Find and compress logs older than 7 days for storage optimization.
Backup Verification
Verify that daily backups were created in the last 24 hours.
Find by Modification Time (Minutes): find . -type f -mmin -5
Commands:
find . -type f -mmin -5 (modified within 5 minutes)
DevOps Use Cases:
Real-Time File Change Detection
Detect config file changes in the last minute for configuration reload triggers.
CI/CD Artifact Verification
Verify build artifacts were recently created in the last 5 minutes.
Find by Permissions: find . -type f -perm 777
Commands:
find . -type f -perm 777 (world-readable, writable, executable files)
DevOps Use Cases:
Security Audit - World-Writable Files
Identify world-writable files that could pose security risks in production.
Kubernetes Secret File Permissions
Verify secret files have restrictive permissions (not world-readable).
Find Empty Files: find . -type f -empty
Command: find . -type f -empty
DevOps Use Cases:
Cleanup Incomplete Artifacts
Remove empty build cache files to free up disk space.
Find Non-Empty Files: find . -type f -not -empty
Command: find . -type f -not -empty
DevOps Use Cases:
Verify Non-Empty Logs
Ensure error log files have content before archiving.
Part 7: Bulk Operations - xargs
Delete Old Files: find . -type f -mtime +2|xargs rm
Commands:
find . -type f -mtime +2|xargs rm (delete files older than 2 days)
find . -type f -mtime +365|xargs rm
DevOps Use Cases:
Automated Disk Cleanup
Delete temporary files older than 7 days to prevent disk space issues.
Archive Old Build Artifacts
Archive old Jenkins build artifacts for long-term storage.
Find with Depth Limit: find . -iname "test" -maxdepth 1
Commands:
find . -type f -iname "test" -maxdepth 1
find . -type d -iname "test" -maxdepth 2
find . -iname "test" -maxdepth 1
DevOps Use Cases:
Shallow Directory Search
Limit deep filesystem searches to improve performance in large filesystems.
Configuration File Location
Search only top-level /etc directory for application config files.
Part 8: File Linking
Soft Link (Symbolic Link): ln -s test1 softlink
Commands:
ln -s /home/test/test1 softlink
DevOps Use Cases:
Application Version Management
Symlink allows zero-downtime application upgrades by switching the link.
Kubernetes ConfigMap Mounting
Create environment-specific symlinks for flexible configuration management.
Hard Link: ln /home/test/test1 hardlink
Command: ln /home/test/test1 hardlink
DevOps Use Cases:
Disaster Recovery Backup
Hard links create instant backups without additional disk space for frequently accessed files.
System Info: uname -a
Command: uname -a
DevOps Use Cases:
OS Compatibility Check in Terraform
Detect OS for platform-specific infrastructure provisioning.
OS Release Info: cat /etc/os-release
Command: cat /etc/os-release
DevOps Use Cases:
Container Base Image Verification
Verify correct OS version in container image for compliance.
Hostname: hostname
Command: hostname
DevOps Use Cases:
Terraform Naming Convention
Use hostname for dynamic configuration and logging in multi-node deployments.
Logged-in Users Count: who|wc -l
Command: who|wc -l
DevOps Use Cases:
Session Monitoring for Security
Track concurrent user sessions for security compliance.
Current User: whoami
Command: whoami
DevOps Use Cases:
Permission Verification in Scripts
Ensure script runs with correct user privileges before performing privileged operations.
Part 10: Background Process Management
No-Hangup Process: nohup ./script.sh &
Command: nohup ./script.sh &
DevOps Use Cases:
Long-Running Deployment Script
Run deployment that survives SSH session disconnect.
Background Health Check
Continuous health checking that persists even after terminal logout.
Part 11: System Monitoring
Real-Time Process Monitoring: top
Command: top
DevOps Use Cases:
Container Resource Monitoring
Monitor process resource usage inside running containers.
Memory Leak Detection
Track memory consumption of application processes in automated monitoring script.
Part 12: Remote Access and File Transfer
Secure Shell Access: ssh
Commands:
ssh -i demo.pem user@server
DevOps Use Cases:
Bastion Host Jump through SSH
Access private servers through jump host in restricted networks.
Execute Remote Commands in Terraform
Secure Copy Protocol: scp
Commands:
scp file_name user@server:/tmp
scp file_name user@server:/home/ubuntu
scp -r directory user@server:/path
DevOps Use Cases:
Deploy Application Binary
Transfer compiled application to production servers.
Batch Configuration Distribution
Distribute configuration files to multiple servers.
Rsync for Efficient Transfer: rsync
Command: rsync file user@server:/home/temp
DevOps Use Cases:
Incremental Backup
Efficiently sync only changed files to backup server, removing deleted files.
Database Replication
Sync database files to replica excluding logs.
Part 13: Network Diagnostics
Test Connectivity: ping
Command: ping ip_address or ping hostname or ping google.com
DevOps Use Cases:
Kubernetes Service Discovery Health Check
Verify DNS resolution in Kubernetes cluster for service discovery.
Network Availability Script
Check reachability of all servers in a cluster.
Telnet Connection Test: telnet
Command: telnet ip or telnet dns_name [port 23]
DevOps Use Cases:
Database Port Connectivity Check
Verify database server is listening on correct port.
Port Availability Verification
Test SSL/TLS port connectivity before traffic routing.
Network Port Monitoring: netstat -na|grep 8080
Command: netstat -na|grep 8080
DevOps Use Cases:
Service Port Binding Verification
Verify application is listening on expected port with process PID.
Connection State Analysis
Count active connections to load balancer for traffic analysis.
Port Conflict Detection
Detect port conflicts before starting new services in deployment automation.
Real-World DevOps Pipeline Example
Here's how these commands work together in a complete CI/CD deployment workflow:
This example demonstrates:
find with xargs for cleanup
sed for configuration management
scp for remote file transfer
ssh for remote command execution
chown for permission management
ps and netstat for verification