Linux Commands Cheat Sheet

Common Linux commands: file/dir, process, network, permission and monitoring commands with notes, for quick lookup while working.

How It Works

The Linux filesystem follows the FHS (Filesystem Hierarchy Standard): / is root, /bin holds base commands, /etc config, /home user data, /var variable data (logs). "Everything is a file" — hardware, processes and pipes appear under /dev and /proc.

The shell pipe (|) feeds one command's output into the next and redirection (> , <) attaches standard streams to files — the core philosophy of composing small tools to solve big problems (do one thing well). Typical tasks: ls/cp/mv/rm for files, chmod/chown for permissions, ps/kill for processes, apt/dnf for packages.

When to Use This Table

This table is for looking up common flag combinations for a Linux command. It is grouped by files, text, processes, disk and network, and permissions, covering the commands you meet daily in operations and development. It is faster than man pages but not a replacement for them.

When not to consult it: you are learning shell syntax itself (pipes, redirection, job control) or debugging a specific error message. Those need man pages and version-specific documentation, because Linux flags vary considerably across distributions and versions.

Rule of thumb: does it change state? Read-only commands such as ls, grep, cat and find are safe; rm, mv, chmod and dd alter data, and rm -rf, dd of=/dev/…, chmod -R 777 deserve a second look at the path before running anywhere that matters.

Mind how sudo interacts with redirection: sudo echo x > /root/f fails, because the redirection is performed by the current shell rather than the elevated process. Either switch with sudo -i first, or use sudo tee.

Boundaries and Common Pitfalls

  • find -exec and xargs both have argument limits and quoting traps

    find . -name "*.log" -exec rm {} ; spawns a process per file (slow but safe), while -exec rm {} + batches them (fast). With xargs you must add -0 alongside find -print0, otherwise filenames containing spaces or newlines get split incorrectly — common when walking git checkouts or node_modules. Confirm the match set first with -print or -exec echo {} ; before deleting.

  • Commands in a pipeline see no interactive input and lose terminal capabilities

    Putting an interactive command in a pipeline breaks it: less, vim and top skip interaction entirely, and ssh without a tty fails with no tty present and no askpass program specified. Keep such commands out of pipes, or pass the flags explicitly (ssh -t, docker exec -it). In the other direction, grep does not paginate inside a pipe, so output can be long and you may want to append | less.

  • Pipes and redirection swallow errors, which scripts most often miss

    For cmd1 | cmd2 the exit code is cmd2 status, so cmd1 crashing does not fail the whole pipeline; the same applies to cmd > out.log 2>&1. In scripts, enable set -o pipefail and inspect ${PIPESTATUS[@]} to check each stage. Also note that cmd > out.log truncates first (use >> to append), and that the position of 2>&1 matters — it must come after >file, otherwise stderr still points at the terminal.

How This Relates to Neighbours

For the full flag surface and POSIX/GNU differences, use man pages and your distribution documentation; this table is a quick set of common combinations.

For diagnosing disk or network performance, interpreting ss, df, du or top matters more than the commands themselves, and that analysis is out of scope here.

Managing systemd units, journal logs, users and permissions is a systems topic that needs study rather than lookup.

If the goal is a reusable shell script, robustness (error handling, quoting, cleanup) needs deliberate design; this table only shows individual command usage.

Practical Snippet

Key points: (1) pair find with xargs using -0 (alongside find -print0) or filenames with spaces or newlines get split, and confirm the match set with -exec echo {} ; before deleting; (2) a pipeline hides upstream errors, so enable set -o pipefail and inspect PIPESTATUS per stage; (3) > truncates first, use >> to append, and 2>&1 must come after >file; (4) sudo echo > /root/f fails because redirection is done by the current shell — use sudo -i or sudo tee.

# ① find + xargs:文件名含空格/换行时必须用 -0
find . -name '*.log' -print0 | xargs -0 rm --
find . -name '*.log' -exec rm {} +          # 批量,快
find . -name '*.log' -exec echo {} ;      # 删之前先确认命中范围

# ② 管道会吞错误,脚本里必须开 pipefail
set -o pipefail
curl -sS https://x.dev/a.log | grep -i error
rc=("${PIPESTATUS[@]}")            # bash: 分别看每段退出码
printf 'curl=%s grep=%s
' "${rc[0]}" "${rc[1]}"

# ③ 重定向:> 会先清空,2>&1 位置有讲究
cmd >> app.log 2>&1               # 追加,stderr 也进文件
cmd > out.log                      # ⚠️ 先清空 out.log
cmd 2>&1 > out.log                 # ⚠️ stderr 仍指向终端(顺序错了)

# ④ sudo 与重定向:重定向由当前 shell 执行,不是提权后的进程
sudo echo x > /root/f             # ❌ permission denied
sudo -i                            # ✅ 先切到 root
echo x > /root/f                   #    再执行
# 或者用 tee
echo x | sudo tee /root/f          # ✅ 一步完成

# ⑤ 只读排查三件套(不改任何状态,可放心跑)
ss -tlnp                           # 谁在监听
ps aux --sort=-%mem | head -11     # 内存占用 top 10
du -sh /var/log/* | sort -h | tail # 哪些日志目录占空间

Practical Notes

  • rm -rf with an empty variable deletes the current directoryWhen DIR is unset, rm -rf $DIR/ becomes rm -rf /. In scripts, always quote and assert non-emptiness: : "${DIR:?}" before rm -rf "$DIR". Moving to a staging directory or using trash-cli further reduces the blast radius.
  • tail -f does not exit when the pipe breaks and misses rotated filesAfter log rotation or truncation, tail -f keeps following the old inode and shows nothing new. Use tail -F (capital F) to follow rotated logs: it reopens the file after replacement.
  • find -exec and piped xargs differ on spacesfind -exec cmd {} + passes filenames with spaces correctly, whereas find | xargs is only safe with -print0 paired with xargs -0. When filenames may contain spaces or newlines, prefer the former.

Data Sources

  • POSIX.1-2017
  • GNU Coreutils manual
  • Distribution man pages

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

CommandDescription
lsList directory contents (-l long, -a include hidden)
cdChange directory (cd ~ home)
pwdPrint working directory (absolute path)
cpCopy file/dir (-r recursive)
mvMove or rename
rmRemove (-r recursive, -f force)
mkdirMake directory (-p recursive)
rmdirRemove empty directory
catPrint entire file
lessPaginated view (scroll up/down)
headShow first lines (-n count)
tailShow last lines (-f follow)
grepText search (-r recursive, -i ignore case)
findFind files by criteria
chmodChange file permissions (rwx)
chownChange file owner/group
psList processes (aux full format)
topReal-time process/resource monitor
killTerminate process (kill -9 force)
dfDisk space usage (-h human)
duDirectory/file size (-sh summary)
freeMemory usage (-h human)
unameKernel info (-a all)
uptimeUptime and load average
tarArchive/extract (-czf compress, -xzf extract)
sshSecure remote login
scpSecure remote copy
rsyncIncremental file sync
curlSend HTTP request / download
wgetCommand-line download
ssShow network connections (-tlnp)
pingTest network connectivity
ipShow/configure network interfaces
systemctlManage system services
crontabManage scheduled jobs (-e edit)
historyShow command history

Frequently Asked Questions

How do I recursively find a file type?

Use find . -name "*.log" to search the current dir and subdirs; add -type f for files only, -mtime -1 for files changed within a day.

How do I watch a log file in real time?

Use tail -f app.log to stream new lines; pipe to grep to filter: tail -f app.log | grep ERROR.

How do I make a script executable?

Use chmod +x script.sh to grant owner execute; for others too use chmod 755 script.sh.

How do I keep a process running in the background?

Use nohup cmd & to survive hangup, or register a systemd service managed by systemctl that auto-restarts on reboot.