Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

20 Essential Linux Commands Every Ops Engineer Must Master
Operations 45 min read

20 Essential Linux Commands Every Ops Engineer Must Master

This article details 20 essential Linux commands for operations engineers, covering file management, text processing, process control, network diagnostics, and system monitoring with practical examples and common parameter combinations for real-world usage.

Introduction

Linux command-line proficiency is fundamental for daily operations, troubleshooting, performance tuning, and service deployment. This guide selects 20 high-frequency commands used in production environments, grouped into file and directory operations, text processing, process management, network diagnostics, system information, and other utilities.

Target Audience

Junior Linux operations engineers

Developers needing quick command-line onboarding

System administrators performing system management and fault diagnosis

Job seekers preparing for operations-related technical interviews

DevOps engineers requiring basic Linux operation skills

These commands are universal across physical machines, virtual machines, containers, and cloud instances running Linux.

Command Categories

File and directory operations: ls, cd, pwd, find, du Text processing: grep, awk, sed, tail Process management: ps, top, kill Network diagnostics: ping, telnet, netstat, ss System information: df, free, uptime Other tools: tar,

curl

Learning Principles

Master basic usage first, then advance to advanced features

Focus on the most commonly used parameter combinations

Deepen understanding through practical examples

Learn to read man pages and --help output

Practice extensively in test environments to avoid mistakes

Safety Considerations

Use caution with commands that delete or overwrite data

Validate operations in a test environment before production

Preview batch operations with echo or dry-run modes

Avoid executing high-risk commands directly as root

Detailed Command Reference

1. ls - List Directory Contents

Basic syntax:

ls [options] [path]

Common Options

# Show detailed information
ls -l
# Show hidden files
ls -a
# Human-readable file sizes
ls -lh
# Sort by modification time
ls -lt
# Sort by file size
ls -lS
# Recursively list subdirectories
ls -R
# Reverse sort order
ls -lr

Practical Examples

# Top 10 largest files in current directory
ls -lSh | head -11
# 5 most recently modified files
ls -lt | head -6
# Count files in a directory
ls /var/log | wc -l
# List only directories
ls -l | grep "^d"

Notes

ls -l

shows modification time (mtime) ls -a includes . and .. For symlinks, ls -l displays link size, not target file size

2. cd - Change Directory

Basic syntax:

cd [path]

Common Tricks

# Go to home directory
cd ~
cd
# Go to parent directory
cd ..
# Go up two levels
cd ../..
# Return to previous directory
cd -
# Go to root directory
cd /
# Go to another user's home
cd ~username

Practical Examples

# Quickly switch between two directories
cd /var/log
# do some work
cd /etc
# need to go back to /var/log
cd -
# Switch to sibling directory
cd ../apache2  # from /var/log/nginx to /var/log/apache2

Notes

cd

without arguments equals cd ~ Quote or escape directory names containing spaces cd - prints the new directory path

3. pwd - Print Working Directory

Basic syntax:

pwd [options]

Common Options

# Show physical path (resolve symlinks)
pwd -P
# Show logical path (default, keep symlinks)
pwd -L

Practical Examples

# Confirm current directory
pwd
# /home/user/project
# Get script directory in a script
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
echo "Script located at: $SCRIPT_DIR"
# Compare logical vs physical path
cd /opt/app  # assume symlink to /usr/local/myapp
pwd -L  # /opt/app
pwd -P  # /usr/local/myapp

Notes

Output is always an absolute path

In scripts, be aware of symlink effects

4. find - Search for Files

Basic syntax:

find [path] [conditions] [actions]

Common Conditions

# By name
find /var/log -name "*.log"
# Case-insensitive name
find /var/log -iname "*.LOG"
# By type (f=file, d=directory, l=symlink)
find /etc -type f
# By size
find /var/log -size +100M
find /tmp -size -1k
# By modification time
find /var/log -mtime -7   # last 7 days
find /tmp -mtime +30      # older than 30 days
# By permissions
find /var/www -perm 777
# By user
find /home -user nginx
# By group
find /var -group www-data

Common Actions

# List found files (default)
find /var/log -name "*.log"
# Show detailed info
find /var/log -name "*.log" -ls
# Execute command on each
find /var/log -name "*.log" -exec ls -lh {} \;
# Delete found files
find /tmp -name "*.tmp" -delete
# Interactive delete confirmation
find /tmp -name "*.tmp" -ok rm {} \;

Practical Examples

# Find log files >100MB and sort by size
find /var/log -type f -size +100M -exec ls -lh {} \; | sort -k5 -hr
# Delete logs older than 30 days
find /var/log -type f -name "*.log.*" -mtime +30 -delete
# Change permissions of 777 files to 644
find /var/www -type f -perm 777 -exec chmod 644 {} \;
# Find empty directories
find /tmp -type d -empty
# Files modified within time range
find /var/log -type f -mtime 0          # last 24 hours
find /var/log -type f -mtime +7 -mtime -14  # 7-14 days ago
# Find files containing specific content
find /etc -type f -name "*.conf" -exec grep -l "server_name" {} \;

Notes

-delete

is irreversible; preview with -ls first -exec uses {} as placeholder and \; as terminator -ok prompts for each file; use cautiously in production -mtime +30 means older than 30 days; -mtime -7 means within last 7 days

Large directories may cause performance issues

5. du - Disk Usage

Basic syntax:

du [options] [path]

Common Options

# Human-readable sizes
du -h
# Summary for a directory
du -sh /var/log
# Limit depth
du -h --max-depth=1 /var
# Sort by size
du -h /var/log | sort -hr | head -10
# Include files
du -ah /var/log
# Grand total
du -ch /var/log | tail -1

Practical Examples

# Size of top-level directories under root
du -sh /* 2>/dev/null | sort -hr
# Top 10 directories under /var with depth 2
du -h /var --max-depth=2 | sort -hr | head -10
# Top 10 files under /var/log
du -ah /var/log | sort -hr | head -10
# Current directory total
du -sh .
# Exclude patterns
du -sh /var --exclude="*.log"

Notes

du

reports actual disk usage

For sparse files, du shows smaller size than ls -l Large directories may be slow 2>/dev/null suppresses permission errors

6. grep - Text Search

Basic syntax:

grep [options] [pattern] [file]

Common Options

# Ignore case
grep -i "error" /var/log/syslog
# Show line numbers
grep -n "error" /var/log/syslog
# Context lines
grep -A 3 "error" /var/log/syslog  # after 3 lines
grep -B 3 "error" /var/log/syslog  # before 3 lines
grep -C 3 "error" /var/log/syslog  # both sides 3 lines
# Recursive search
grep -r "server_name" /etc/nginx/
# Only filenames
grep -l "error" /var/log/*.log
# Count matches
grep -c "error" /var/log/syslog
# Invert match
grep -v "INFO" /var/log/app.log
# Extended regex
grep -E "error|warn|fail" /var/log/syslog
# Perl regex
grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" /var/log/access.log

Practical Examples

# Count error lines
grep -i "error" /var/log/app.log | wc -l
# Multiple keywords
grep -E "error|warn|fail" /var/log/syslog
# Extract IP addresses
grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" /var/log/access.log
# Exclude DEBUG lines
grep -v "DEBUG" /var/log/app.log
# Recursive search in config files
grep -r "listen 80" /etc/nginx/ --include="*.conf"
# Pipeline combination
ps aux | grep nginx | grep -v grep
# Context around OutOfMemory
grep -C 5 "OutOfMemory" /var/log/app.log

Notes

Default uses basic regex; some characters need escaping -E enables extended regex (no escaping for +, ?, |) -P uses Perl regex (most powerful but not universally available)

Recursive search on large trees can be slow grep -v grep filters out the grep process itself

7. awk - Text Processing

Basic syntax:

awk [options] 'pattern {action}' [file]

Common Scenarios

# Print specific columns
awk '{print $1}' file.txt
awk '{print $1, $3}' file.txt
# Custom delimiter
awk -F: '{print $1}' /etc/passwd
# Filter and print
awk '$3 > 1000 {print $1}' /etc/passwd
# Count lines
awk 'END {print NR}' file.txt
# Sum column
awk '{sum += $2} END {print sum}' file.txt
# Formatted output
awk '{printf "%-10s %s
", $1, $2}' file.txt

Practical Examples

# Count status codes in nginx access log
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
# Extract user and CPU from ps
ps aux | awk '{print $1, $3}'
# Filter processes with CPU > 10%
ps aux | awk '$3 > 10 {print $0}'
# Sum disk usage percentages
df -h | awk 'NR>1 {gsub(/%/, "", $5); sum += $5} END {print sum}'
# Format /etc/passwd output
awk -F: '{printf "User: %-15s UID: %s
", $1, $3}' /etc/passwd
# Multiple delimiters
awk -F'[: ]' '{print $1, $3}' file.txt
# Print lines matching pattern
awk '/error/ {print $0}' /var/log/app.log

Notes

$0

= whole line, $1 = first column, etc. NR = current line number, NF = number of fields -F sets delimiter (default whitespace) awk streams input, suitable for large files

8. sed - Stream Editor

Basic syntax:

sed [options] 'command' [file]

Common Commands

# Replace first occurrence per line
sed 's/old/new/' file.txt
# Replace all occurrences
sed 's/old/new/g' file.txt
# Delete lines matching pattern
sed '/pattern/d' file.txt
# Print matching lines only
sed -n '/pattern/p' file.txt
# Replace on specific line
sed '3s/old/new/' file.txt
# Delete empty lines
sed '/^$/d' file.txt
# Append after match
sed '/pattern/a
ew line' file.txt
# Insert before match
sed '/pattern/i
ew line' file.txt
# Edit file in-place
sed -i 's/old/new/g' file.txt

Practical Examples

# Batch replace in nginx configs
sed -i 's/listen 80/listen 8080/g' /etc/nginx/sites-enabled/*.conf
# Remove empty lines from log
sed '/^$/d' /var/log/app.log > /var/log/app_clean.log
# Extract lines 10-20
sed -n '10,20p' file.txt
# Comment out line 5
sed -i '5s/^/# /' config.conf
# Replace IP addresses
sed -i 's/192\.168\.1\.10/192.168.1.20/g' *.conf
# Insert line at beginning
sed -i '1i\# Configuration file' config.conf
# Delete lines containing DEBUG
sed -i '/DEBUG/d' /var/log/app.log

Notes

-i

modifies file directly; backup first -i.bak creates backup before editing

Escape special regex characters

By default sed outputs to stdout, not modifying original

9. tail - View File End

Basic syntax:

tail [options] [file]

Common Options

# Last 10 lines (default)
tail file.txt
# Last 20 lines
tail -n 20 file.txt
tail -20 file.txt
# Follow new content in real-time
tail -f /var/log/syslog
# Last 100 bytes
tail -c 100 file.txt
# Follow multiple files
tail -f /var/log/nginx/access.log /var/log/nginx/error.log
# Start from line 10
tail -n +10 file.txt

Practical Examples

# Monitor log in real-time
tail -f /var/log/app.log
# Follow and filter for ERROR
tail -f /var/log/app.log | grep "ERROR"
# Last 50 lines and search
tail -n 50 /var/log/app.log | grep "timeout"
# Multiple logs
tail -f /var/log/nginx/*.log
# View compressed log tail
zcat /var/log/syslog.1.gz | tail -20

Notes

tail -f

runs continuously; press Ctrl+C to exit

For rotated logs, tail -f may miss new content; re-run

Some systems support tail -F to auto-detect rotation

10. ps - Process Snapshot

Basic syntax:

ps [options]

Common Options

# All processes
ps aux
ps -ef
# By user
ps -u nginx
# Process tree
ps auxf
ps -ejH
# Specific PID
ps -p 1234
# Threads
ps -eLf
# Custom columns
ps -eo pid,comm,pcpu,pmem

Practical Examples

# Find nginx processes
ps aux | grep nginx
# Sort by CPU usage
ps aux --sort=-%cpu | head -10
# Sort by memory usage
ps aux --sort=-%mem | head -10
# Detailed info for nginx PIDs
ps -fp $(pgrep nginx)
# Process start times
ps -eo pid,lstart,cmd
# Count processes for user
ps -u www-data | wc -l
# Find zombie processes
ps aux | awk '$8 ~ /Z/ {print $0}'

Notes

ps aux

and ps -ef differ slightly in format but show similar info ps is a static snapshot, not real-time

Process states: R=running, S=sleeping, D=uninterruptible sleep, Z=zombie, T=stopped %CPU and %MEM are instantaneous values

11. top - Real-time Process Monitor

Basic syntax:

top [options]

Interactive Keys

# Sort by CPU
P
# Sort by memory
M
# Sort by time
T
# Show full command
c
# Kill process
k
# Change refresh interval
d
# Quit
q
# Filter by user
u
# Show threads
H

Common Options

# Batch mode (for scripts)
top -b -n 1
# Monitor specific PID
top -p 1234
# Refresh interval
top -d 2
# Specific user
top -u nginx

Practical Examples

# View system load (first line load average)
top
# Monitor nginx processes
top -p $(pgrep nginx | tr '
' ',' | sed 's/,$//')
# Snapshot to file
top -b -n 1 > top.txt
# Thread-level view
top -H -p 1234
# Top 10 CPU consumers
top -b -n 1 | head -17 | tail -10

Notes

Default sort by CPU usage

Third line %Cpu(s) shows CPU state breakdown us =user, sy =system, id =idle, wa =iowait %CPU is sum across all cores, can exceed 100%

12. kill - Terminate Processes

Basic syntax:

kill [options] [PID]

Common Signals

# Default TERM (15)
kill 1234
# Force kill KILL (9)
kill -9 1234
# Reload config HUP (1)
kill -HUP 1234
# Stop process STOP (19)
kill -STOP 1234
# Continue process CONT (18)
kill -CONT 1234
# List all signals
kill -l

Practical Examples

# Kill all nginx processes
pkill nginx
# or
killall nginx
# Graceful nginx reload
kill -HUP $(cat /var/run/nginx.pid)
# Kill by pattern
ps aux | grep "process_name" | grep -v grep | awk '{print $2}' | xargs kill
# Kill all processes of a user
pkill -u username
# Force kill stuck process
kill -9 1234

Notes

kill -9

cannot be caught; may cause data loss

Prefer kill (TERM) for graceful shutdown; escalate to kill -9 only if needed killall and pkill match by name; may accidentally kill same-named processes

Killing parent process makes children orphans

13. df - Disk Free Space

Basic syntax:

df [options] [filesystem]

Common Options

# Human-readable
df -h
# Show filesystem type
df -T
# Inode usage
df -i
# Local filesystems only
df -l
# Filesystem containing a file
df /var/log/syslog
# Specific type
df -t ext4

Practical Examples

# Disk usage overview
df -h
# Root partition usage
df -h /
# Inode usage
df -i
# Sort by usage percentage
df -h | sort -k5 -rh
# All ext4 filesystems
df -t ext4
# Exclude tmpfs and devtmpfs
df -x tmpfs -x devtmpfs

Notes

df

shows filesystem-level usage

If df shows 100% but du doesn't account for it, deleted files may still be held open by processes df -i checks inode exhaustion, which also prevents file creation

Overlapping mounts can affect output

14. free - Memory Usage

Basic syntax:

free [options]

Common Options

# Human-readable
free -h
# Megabytes
free -m
# Gigabytes
free -g
# Continuous display
free -s 2  # every 2 seconds
# Wide output
free -w

Practical Examples

# Memory overview
free -h
# Continuous monitoring
free -h -s 2
# Available memory only
free -h | awk 'NR==2 {print "Available memory: " $7}'
# Calculate usage percentage
free | awk 'NR==2 {printf "Memory usage: %.2f%%
", $3/$2*100}'

Notes

available

column is more meaningful than

free
buff/cache

is reclaimable system cache

High swap usage indicates physical memory pressure

Output format varies slightly across versions

15. uptime - System Uptime and Load

Basic syntax:

uptime

Output Example

14:30:45 up 10 days,  3:21,  2 users,  load average: 2.35, 1.80, 1.50

Field Meanings

14:30:45

: current time up 10 days, 3:21: system uptime 2 users: logged-in user count load average: 2.35, 1.80, 1.50: 1, 5, 15 minute load averages

Practical Examples

# Quick load check
uptime
# Extract 1-minute load in script
LOAD=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
echo "1-minute load: $LOAD"
# Watch load every 5 seconds
watch -n 5 uptime

Notes

Interpret load average relative to CPU core count

Load approaching 2x core count warrants attention

High load may indicate I/O bottleneck, not just CPU

16. ping - Network Connectivity Test

Basic syntax:

ping [options] [target]

Common Options

# Send 4 packets
ping -c 4 baidu.com
# Set packet size
ping -s 1000 baidu.com
# Set timeout
ping -W 2 baidu.com
# Set interval
ping -i 0.5 baidu.com
# Quiet mode (summary only)
ping -q -c 10 baidu.com
# Flood mode (fast, needs root)
ping -f baidu.com

Practical Examples

# Test connectivity to Google DNS
ping -c 4 8.8.8.8
# Test gateway connectivity
ping -c 4 $(ip route | grep default | awk '{print $3}')
# Test DNS resolution
ping -c 4 baidu.com
# Batch ping subnet
for ip in 192.168.1.{1..10}; do
  ping -c 1 -W 1 $ip &>/dev/null && echo "$ip is up" || echo "$ip is down"
done
# Latency statistics
ping -c 100 baidu.com | tail -1

Notes

Some servers block ICMP; ping failure doesn't mean host is down

Without -c, ping runs indefinitely; Ctrl+C to stop

Firewalls may drop ICMP packets

High latency variance suggests network instability

17. telnet - Port Connectivity Test

Basic syntax:

telnet [host] [port]

Practical Examples

# Test HTTP port
telnet baidu.com 80
# Test MySQL port
telnet 192.168.1.10 3306
# Test SSH port
telnet 192.168.1.10 22
# Scripted port test
timeout 2 telnet 192.168.1.10 80 &>/dev/null
if [ $? -eq 0 ]; then
  echo "Port open"
else
  echo "Port unreachable"
fi
# Batch port scan
for port in 80 443 3306 6379; do
  timeout 1 telnet 192.168.1.10 $port &>/dev/null && echo "Port $port open" || echo "Port $port closed"
done

Notes

After successful connection, press Ctrl+] then type quit to exit

Firewall blocking causes telnet to hang

Not installed by default on some systems

Prefer nc or ss for port testing

18. netstat - Network Connections

Basic syntax:

netstat [options]

Common Options

# All connections
netstat -a
# TCP only
netstat -t
# UDP only
netstat -u
# Listening ports
netstat -l
# Show PID/Program
netstat -p
# Numeric addresses (no DNS)
netstat -n
# Common combos
netstat -antp  # all TCP, numeric, with PID
netstat -anlp  # all listening, numeric, with PID

Practical Examples

# Listening ports
netstat -tuln
# Connections on port 80
netstat -antp | grep :80
# Connection state counts
netstat -an | awk '/^tcp/ {print $6}' | sort | uniq -c | sort -rn
# Top source IPs
netstat -an | grep ESTABLISHED | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -rn | head -10
# Process-specific connections
netstat -antp | grep nginx

Notes

netstat

is being replaced by ss on newer systems -n avoids DNS lookups for speed

States: LISTEN, ESTABLISHED, TIME_WAIT, CLOSE_WAIT, etc.

Many TIME_WAIT connections often indicate excessive short-lived connections

19. ss - Socket Statistics

Basic syntax:

ss [options]

Common Options

# All connections
ss -a
# TCP
ss -t
# UDP
ss -u
# Listening
ss -l
# Show process
ss -p
# Numeric
ss -n
# Common combos
ss -antp   # all TCP
ss -tulnp  # all listening

Practical Examples

# Listening ports
ss -tuln
# Port 80 connections
ss -antp | grep :80
# State counts
ss -an | awk '{print $2}' | sort | uniq -c | sort -rn
# Process connections
ss -antp | grep nginx
# Top source IPs
ss -tn | awk 'NR>1 {print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -rn | head -10

Notes

ss

is faster than netstat; recommended

Output format similar but not identical to netstat May not be installed by default on some systems

20. tar - Archive and Compress

Basic syntax:

tar [options] [files]

Common Options

# Create archive
tar -cvf archive.tar files/
# Create gzip compressed
tar -czvf archive.tar.gz files/
# Create bzip2 compressed
tar -cjvf archive.tar.bz2 files/
# Create xz compressed
tar -cJvf archive.tar.xz files/
# Extract
tar -xvf archive.tar
# Extract to directory
tar -xvf archive.tar -C /tmp/
# List contents
tar -tvf archive.tar
# Append file
tar -rvf archive.tar newfile.txt
# Exclude patterns
tar -czvf archive.tar.gz --exclude="*.log" files/

Practical Examples

# Backup with date
tar -czvf /backup/www_$(date +%Y%m%d).tar.gz /var/www/
# Extract to /opt/
tar -xzvf archive.tar.gz -C /opt/
# Extract specific files
tar -xzvf archive.tar.gz file1.txt file2.txt
# View archive
tar -tzvf archive.tar.gz | less
# Exclude node_modules and .git
tar -czvf backup.tar.gz --exclude="node_modules" --exclude=".git" project/
# Split large archive
tar -czvf - bigdir/ | split -b 100M - backup.tar.gz.part
# Reassemble and extract
cat backup.tar.gz.part* | tar -xzvf -

Notes

-c

create, -x extract, -t list; cannot combine -z gzip, -j bzip2, -J xz

Extraction auto-detects compression format

Omit -v for speed on large archives

Use relative paths when creating archives to avoid overwriting system files

21. curl - HTTP Client (Bonus)

Basic syntax:

curl [options] [URL]

Common Options

# GET request
curl http://example.com
# POST request
curl -X POST http://example.com
# POST form data
curl -X POST -d "key=value" http://example.com
# POST JSON
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://example.com
# Custom header
curl -H "Authorization: Bearer token" http://example.com
# Save output
curl -o output.txt http://example.com
# Download file
curl -O http://example.com/file.tar.gz
# Show headers only
curl -I http://example.com
# Follow redirects
curl -L http://example.com
# Timeouts
curl --connect-timeout 5 --max-time 10 http://example.com
# Skip SSL verification
curl -k https://example.com
# Verbose debug
curl -v http://example.com

Practical Examples

# Test API
curl -X GET http://api.example.com/users
# JSON login
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"123456"}' \
  http://api.example.com/login
# Download
curl -O http://example.com/file.tar.gz
# Measure response time
curl -o /dev/null -s -w "Time: %{time_total}s
" http://example.com
# Batch URL test
for url in url1 url2 url3; do
  curl -o /dev/null -s -w "$url: %{http_code} %{time_total}s
" $url
done
# File upload
curl -F "file=@/path/to/file" http://example.com/upload

Notes

-d

defaults to application/x-www-form-urlencoded JSON requires explicit Content-Type header -k disables SSL verification; only for testing -L follows redirects; some APIs require it

Summary

The 20 commands covered span the core daily scenarios for operations engineers: file management, text processing, process control, network diagnostics, and system monitoring. Mastery of these commands is a baseline skill set.

Learning Recommendations

Start with basic usage, then progress to advanced features

Practice heavily in test environments

Learn to read man pages and --help output

Understand underlying principles rather than rote memorization

Apply commands flexibly in real scenarios

Advanced Directions

Learn shell scripting to automate command combinations

Master regular expressions for enhanced text processing

Study performance analysis tools: strace, perf, sar Learn container and orchestration tools: Docker, Kubernetes

Explore monitoring and log analysis stacks: Prometheus, ELK

Command proficiency is only the first step; true expertise comes from production experience and deep understanding of system internals.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

MonitoringOperationsLinuxtroubleshootingshellsystem-administrationbashcommands

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion