Day 4

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:

  1. Application Deployment Pipeline

    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.

  2. Docker Container Access Control

    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.

  3. Backup Restore Operations

    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.

  4. Multi-tenant Infrastructure

    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:

  1. Configuration Templating in CI/CD

    Before deploying to production, replace environment-specific values in config files without manual editing.

  2. Log Sanitization

    Remove sensitive data from logs before shipping them to centralized logging (ELK Stack, Splunk).

  3. 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:

  1. Infrastructure as Code (IaC) Updates

    Update Terraform files in-place to scale up instance types across environments.

  2. Kubernetes Manifest Updates

    Update container image versions in Kubernetes manifests before applying with kubectl apply.

  3. 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:

  1. 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:

  1. Surgical Config File Updates

    Update only the 3rd line where the debug flag is set, avoiding unintended changes elsewhere.

  2. 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:

  1. Large Configuration Files

    Update domain references only in the server block (lines 50-100) of a large Nginx config file.

  2. 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:

  1. Configuration Migration

    Update all database references from line 20 onwards in a configuration file during infrastructure migration.

Commands: sed -n '98p' file | sed -n '2p' file2

DevOps Use Cases:

  1. Extract Build Information

    Extract version information from a specific line in build logs for versioning purposes.

  2. Kubernetes Event Extraction

    Extract a specific line from pod events for debugging.

Command: sed -n '10,20p' file

DevOps Use Cases:

  1. Log Excerpt Extraction

    Extract 50 lines of context around an error timestamp for detailed analysis.

  2. 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:

  1. Remove Configuration Comments

    Remove a deprecated configuration line that breaks newer application versions.

  2. 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:

  1. 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:

  1. Extract IPs from Server List

    Extract usernames running Java processes for audit purposes.

  2. 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:

  1. Extract User and PID from Process List

    Extract username and PID pairs for process killing scripts in automation.

  2. Parse HTTP Access Logs

    Extract IP addresses and HTTP status codes for traffic analysis.


Part 4: Advanced Text Processing - awk

Commands: awk -F " " '{print $2}' test1 | awk -F " " '{print $3}' test1

DevOps Use Cases:

  1. Extract Memory Usage from top

    Extract memory percentage for monitoring and alerting in Prometheus exporter scripts.

  2. 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:

  1. Extract Process Names

    Count frequency of running processes for anomaly detection.

  2. 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:

  1. 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:

  1. Extract Critical Log Data

    Extract timestamp and error code for incident tracking.

  2. 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:

  1. 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:

  1. CI/CD Pipeline Dependency Check

    Verify Docker daemon is running before starting CI/CD jobs.

  2. 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:

  1. 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:

  1. Force Kill Hung Deployment Process

    Force terminate a stuck deployment to allow new deployment to proceed.

  2. 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:

  1. Blue-Green Deployment

    Stop old application, deploy new version, and start service.

  2. 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:

  1. Identify Resource-Heavy Users

    Find top 5 memory-consuming processes for a specific user in performance troubleshooting.

  2. 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:

  1. Automation User Creation

    Create dedicated user for CI/CD pipeline with required group memberships.

  2. 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 . -iname "dir"

  • find /Users/hareeshab/Documents -iname "dir2"

DevOps Use Cases:

  1. Locate Configuration Files

    Find configuration files for backup and version control in multi-server environments.

  2. 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:

  1. 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:

  1. 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:

  1. Log Rotation Automation

    Find and compress logs older than 7 days for storage optimization.

  2. 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)

  • find . -type d -mmin -15

DevOps Use Cases:

  1. Real-Time File Change Detection

    Detect config file changes in the last minute for configuration reload triggers.

  2. 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)

  • find . -type d -perm 644

  • find . -perm 755

DevOps Use Cases:

  1. Security Audit - World-Writable Files

    Identify world-writable files that could pose security risks in production.

  2. 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:

  1. 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:

  1. 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:

  1. Automated Disk Cleanup

    Delete temporary files older than 7 days to prevent disk space issues.

  2. 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:

  1. Shallow Directory Search

    Limit deep filesystem searches to improve performance in large filesystems.

  2. Configuration File Location

    Search only top-level /etc directory for application config files.


Part 8: File Linking

Commands:

  • ln -s test1 softlink

  • ln -s /home/test/test1 softlink

DevOps Use Cases:

  1. Application Version Management

    Symlink allows zero-downtime application upgrades by switching the link.

  2. Kubernetes ConfigMap Mounting

    Create environment-specific symlinks for flexible configuration management.

Command: ln /home/test/test1 hardlink

DevOps Use Cases:

  1. Disaster Recovery Backup

    Hard links create instant backups without additional disk space for frequently accessed files.


Part 9: System Information

System Info: uname -a

Command: uname -a

DevOps Use Cases:

  1. 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:

  1. Container Base Image Verification

    Verify correct OS version in container image for compliance.

Hostname: hostname

Command: hostname

DevOps Use Cases:

  1. 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:

  1. Session Monitoring for Security

    Track concurrent user sessions for security compliance.

Current User: whoami

Command: whoami

DevOps Use Cases:

  1. 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:

  1. Long-Running Deployment Script

    Run deployment that survives SSH session disconnect.

  2. 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:

  1. Container Resource Monitoring

    Monitor process resource usage inside running containers.

  2. 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:

DevOps Use Cases:

  1. Bastion Host Jump through SSH

    Access private servers through jump host in restricted networks.

  2. 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:

  1. Deploy Application Binary

    Transfer compiled application to production servers.

  2. Batch Configuration Distribution

    Distribute configuration files to multiple servers.

Rsync for Efficient Transfer: rsync

Command: rsync file user@server:/home/temp

DevOps Use Cases:

  1. Incremental Backup

    Efficiently sync only changed files to backup server, removing deleted files.

  2. 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:

  1. Kubernetes Service Discovery Health Check

    Verify DNS resolution in Kubernetes cluster for service discovery.

  2. 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:

  1. Database Port Connectivity Check

    Verify database server is listening on correct port.

  2. 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:

  1. Service Port Binding Verification

    Verify application is listening on expected port with process PID.

  2. Connection State Analysis

    Count active connections to load balancer for traffic analysis.

  3. 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

Last updated