Essential Linux Command Cheat Sheet for System Administrators
A comprehensive collection of essential Linux commands covering system shutdown, CPU and kernel inspection, file and directory management, networking tools, performance monitoring, user administration, and common shell utilities, all organized for quick reference by developers and sysadmins.
Basic Operations
Linux Shutdown and Reboot
# Shutdown
shutdown -h now
# Reboot
shutdown -r nowView System and CPU Information
# View kernel information
uname -a
# View kernel version
cat /proc/version
# View current environment variables
env
# View CPU information
cat /proc/cpuinfo
# Count logical CPUs and display model name
cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c
# Count physical CPUs and cores per CPU
cat /proc/cpuinfo | grep physical | uniq -c
# Determine if the current CPU runs in 32‑bit or 64‑bit mode
getconf LONG_BIT
# Verify 64‑bit support ("lm" flag indicates long mode)
cat /proc/cpuinfo | grep flags | grep ' lm ' | wc -lCreate Symbolic Link
ln -s /usr/local/jdk1.8/ jdkRPM Related
# Check if a package is installed via rpm
rpm -qa | grep <package_name>SSH Key Generation
# Generate SSH key
ssh-keygen -t rsa -C [email protected]
# Copy the content of id_rsa.pub to the target server's ~/.ssh/authorized_keys (create the file if it does not exist; set .ssh permissions to 700 and authorized_keys to 600)Command Alias (Rename)
# Add alias to each user's .bash_profile
alias ll='ls -alF'Synchronize Server Time
sudo ntpdate -u ntp.api.bzRun Command in Background
# Run in background with nohup output to nohup.out
nohup xxx &
# Run in background, discard all output
nohup xxx > /dev/null &
# Run in background, redirect both stdout and stderr to a log file
nohup xxx > out.log 2>&1 &Force Active User Logout
# Force logout of a user on a specific TTY
pkill -kill -t <TTY>Find Command Path
which <command>Check Maximum Open File Descriptors
ulimit -nConfigure DNS
vim /etc/resolv.confnslookup – View Domain Routing Table
nslookup google.comLast – Recent Login Information
# Show the last 5 logged‑in accounts
last -n 5Set Fixed IP Address
ifconfig em1 192.168.5.177 netmask 255.255.255.0View Process Environment Variables
# Show environment of a specific process (replace XXXXX with PID)
ps eww -p XXXXXView Process Tree to Locate Server Processes
ps auwxfView Process Startup Path
cd /proc/XXX # replace XXX with PID
ls -all
# The "cwd" entry shows the startup directoryAdd User and Configure sudo Permissions
# Add new user
useradd <username>
passwd <username>
# Grant sudo rights (edit /etc/sudoers)
vim /etc/sudoers
# Add a line such as:
# <username> ALL=(ALL) ALLForce Kill All Processes Matching a Name
ps aux | grep xxx | grep -v grep | awk '{print $2}' | xargs kill -9Disk, File, and Directory Operations
Vim Operations
# Global substitution: replace all occurrences of x with y
:%s/x/y/g
# Move cursor to line start
0
# Move cursor to line end
$
# Jump to file end
Shift+g
# Jump to file start
gg
# Show line numbers
:set nu
# Hide line numbers
:set nonu
# Search forward (press n for next)
/xxx
# Search backward
?xxxEdit Read‑Only File and Save Without Switching Users
# In normal mode
:w !sudo tee %View Disk and Directory Basic Information
# Show mounted filesystems
mount
# Show disk partition usage
df
# Show directory and subdirectory sizes
du -H -h
# Show size of each item in the current directory (non‑recursive)
du -sh *Word Count (wc) Commands
# Count lines in a file
wc -l filename
# Count words in a file
wc -w filename
# Show length of the longest line
wc -L filename
# Count bytes
wc -cCompression and Decompression Commands
Compression
tar czvf xxx.tar <directory_to_compress>
zip -r xxx.zip <directory_to_compress>Decompression
tar zxvf xxx.tar
# Decompress to a specific directory
tar zxvf xxx.tar -C /xxx/yyy/
unzip xxx.zipChange File Owner and Group
chown eagleye.eagleye xxx.logCopy, SCP, and Mkdir
# Copy a file
cp xxx.log
# Force overwrite existing file
cp -f xxx.log
# Copy a directory recursively
cp -r src_dir dst_dir
# Remote copy via scp (specify SSH port)
scp -P <ssh_port> [email protected]:/home/username/xxx /home/xxx
# Create nested directories in one command
mkdir -p /xxx/yyy/zzz
# Batch create directories (e.g., src/{test,main}/{java,resources})
mkdir -p src/{test,main}/{java,resources}Compare Two Files
diff -u 1.txt 2.txtLog Byte Count for Performance Testing
# Output a dot for each iteration; the byte count reflects the number of runs
tail -f xxx.log | pv -btView and Remove Special Characters
# Show special characters
cat -v xxx.sh
# Remove carriage‑return characters (Ctrl+V+Enter to input ^M)
sed -i 's/^M//g' env.shHandle System‑Induced Special Characters in Files
# Convert file to the current system format
cat file.sh > file.sh_bak
# Re‑enter file content and save (Ctrl+D to finish)
cat > file1.sh
# In vim, set file encoding to UTF‑8 and format to Unix
:set fileencoding=utf-8
:w
:set fileformat=unix
# On macOS, use dos2unix to normalize .sh files
find . -name "*.sh" | xargs dos2unixtee – Redirect Output While Displaying on Screen
awk '{print $0}' xxx.log | tee test.logSearch‑Related Commands
grep
# Invert match (show lines that do NOT contain xxx)
grep -v xxx
# Exclude empty lines
grep -v '^$'
# Show line numbers where pattern occurs
grep -n "^abc" file.txt
# Count occurrences of a string
grep -c 'xxx' file.log
# Case‑insensitive search
grep -i 'xxx' file.logawk
# Print lines where the 5th field contains "user" (colon‑delimited)
awk -F ':' '{if ($5 ~ /user/) print $0}' /etc/passwd
# Count occurrences of a character (works for ASCII only)
awk -v RS='character' 'END{print --NR}' file.txtfind
# Find files with .mysql suffix under /home/eagleye
find /home/eagleye -name "*.mysql" -print
# Find files accessed in the last 3 days under /usr
find /usr -atime 3 -print
# Find files modified in the last 5 days under /usr
find /usr -ctime 5 -print
# Find files owned by user jacky with names starting with j under /doc
find /doc -user jacky -name 'j*' -print
# Find files starting with "ja" or "ma" under /doc
find /doc \( -name 'ja*' -o -name 'ma*' \) -print
# Delete all files ending with .bak under /doc
find /doc -name '*bak' -exec rm {} \;Network‑Related Commands
Identify Process Using a Port
lsof -i:<port>Get Local IP Address
/sbin/ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:"iptables
# Show iptables status
service iptables status
# Block an IP address
iptables -I INPUT -s <IP_address> -j DROP
# Unblock the IP address
iptables -D INPUT -s <IP_address> -j DROP
# Open port 9090 for TCP traffic
/sbin/iptables -I INPUT -p tcp --dport 9090 -j ACCEPT
# Start, stop, restart iptables service
/etc/init.d/iptables start
/etc/init.d/iptables stop
/etc/init.d/iptables restartnc – TCP Debugging Tool
# Send contents of data.txt to a remote endpoint
nc 192.168.0.11 8000 < data.txt
# Listen on port 8000 and save the incoming request
nc -l 8000 > received_data
# Keep listening for multiple connections
nc -lk 8000tcpdump
# Capture TCP packets on port 12301 from interface em1
tcpdump -i em1 tcp port 12301 -s 1500 -w abc.pcapTraceroute
# Use ICMP mode
traceroute -I www.163.com
# Start tracing from TTL 3
traceroute -M 3 www.163.com
# Trace to a specific port
traceroute -p 8080 192.168.10.11ss – Socket Statistics
# List all listening sockets
ss -l
# Show sockets with associated processes
ss -pl
# Show all TCP sockets
ss -t -a
# Show all UDP sockets
ss -u -a
# Show established SMTP connections
ss -o state established '( dport = :smtp or sport = :smtp )'
# Show established HTTP connections
ss -o state established '( dport = :http or sport = :http )'
# Find processes using X server sockets
ss -x src /tmp/.X11-unix/*
# Show socket statistics summary
ss -snetstat
# Count connections per IP and total per state
netstat -n | awk '/^tcp/ {n=split($(NF-1),a,":"); if(n<=2) ++S[a[1]]; else ++S[a[4]]; ++st[$NF]; ++total} END {for(i in S) printf("%-20s %s
", i, S[i]); printf("%-20s %s
","TOTAL_IP", length(S)); for(i in st) printf("%-20s %s
", i, st[i]); printf("%-20s %s
","TOTAL_LINK", total)}'
# Show count of each TCP state
netstat -n | awk '/^tcp/ {++state[$NF]} END {for(s in state) print s, "\t", state[s]}'
# List top 20 TIME_WAIT connections
netstat -n | grep TIME_WAIT | awk '{print $5}' | sort | uniq -c | sort -rn | head -n20Linux Performance Monitoring Commands
top
Press uppercase F or O followed by a‑z to sort processes by a column, then press Enter . Press uppercase R to reverse the current sort order.
PID Process ID
PPID Parent Process ID
RUSER Real user name
UID User ID of the process owner
USER Username of the process owner
GROUP Group name of the process owner
TTY Controlling terminal ("?" if none)
PR Priority
NI Nice value (negative = higher priority)
P Last used CPU (relevant on multi‑CPU systems)
%CPU CPU usage percentage since last update
TIME Cumulative CPU time (seconds)
%MEM Physical memory usage percentage
VIRT Virtual memory size (KB)
SWAP Swapped out virtual memory (KB)
RES Resident (non‑swapped) memory size (KB)
CODE Size of executable code (KB)
DATA Size of data + stack (KB)
SHR Shared memory size (KB)
S Process state (D, R, S, T, Z, etc.)
COMMAND Command name or full command line
WCHAN Wait channel (kernel function name if sleeping)
FLAGS Task flags (see sched.h)dmesg – View Kernel Messages
dmesgiostat – Disk I/O Monitoring
iostat -xz 1
# Columns of interest:
# r/s, w/s, rkB/s, wkB/s – reads/writes per second and data volume.
# await – average I/O wait time (ms).
# avgqu‑sz – average number of requests queued.
# %util – device utilization (values >60% may indicate bottlenecks).free – Memory Usage
free -m
# Example output:
# total used free shared buffers cached
# Mem: 1002 769 232 0 62 421
# -/+ buffers/cache: 286 715
# Swap: 1153 0 1153
# "used" (286 MB) reflects memory actually consumed by applications.
# "free" (715 MB) is memory available for new allocations.sar – Network Throughput and TCP Statistics
# Network device throughput
sar -n DEV 1
# TCP connection statistics
# active/s – connections initiated locally per second
# passive/s – connections accepted per second
# retrans/s – retransmissions per second
sar -n TCP,ETCP 1vmstat – CPU, Memory, and I/O Monitoring
# Sample: collect once after a 2‑second interval
vmstat 2 1
# Columns:
# r – processes waiting for CPU (run queue length)
# b – processes in uninterruptible sleep
# swpd – used swap space (KB)
# free – idle memory (KB)
# buff – buffer cache (KB)
# cache – page cache (KB)
# si – swap‑in rate (KB/s)
# so – swap‑out rate (KB/s)
# bi – blocks received from block devices (blocks/s)
# bo – blocks sent to block devices (blocks/s)
# in – interrupts per second
# cs – context switches per second
# us – user CPU time percentage
# sy – system CPU time percentage
# id – idle CPU percentage
# wa – I/O wait CPU percentageSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
