Chuyển đến nội dung

Bài 74 · Practice and Review

Linux and Bash Cheat Sheet

A one-page Linux and Bash cheat sheet: navigation, files, text tools, redirection, quoting, tests, loops, functions, signals, exit codes and handy one-liners.

This page is a compact reference for the Linux command line and Bash scripting: the commands and syntax you reach for every day, in one place. It is not a tutorial. Each section links to the lesson that explains the topic properly, and the trickiest items have a small example you can run and change. Code blocks without a Run button are read-only reminders; many of them need things the sandbox does not have (a real terminal, sudo, a network), so treat them as notes.

Use the search box (Ctrl+K) for anything that is not here. To practise, try the basic problems and the scripting problems, or build one of the projects. Differences between GNU/Linux and macOS/BSD tools are marked with GNU where they matter.

Getting around

Navigation, Filesystem layout

Terminal
pwd                    # print the working directory
cd /var/log            # go to an absolute path
cd ..                  # one level up
cd -                   # back to the previous directory
cd                     # home (same as cd ~)
ls -lah                # long format, all files (including hidden), human sizes
ls -ltr                # newest last
ls -d */               # only the directories
Path Meaning
/ root of the whole tree
~ or $HOME your home directory
. and .. this directory, the parent
/etc system configuration
/var/log logs
/tmp temporary files, cleared on reboot
/usr/bin, /bin commands
/proc, /dev kernel and device interfaces that look like files

Files and directories

Creating files, Copy, move, remove, Links

Terminal
touch a.txt                  # create an empty file or update its time
mkdir -p a/b/c               # create nested directories
cp -a src/ dst/              # copy recursively, keep permissions and times
mv old new                   # rename or move
rm -r dir                    # delete a directory tree (no undo!)
rmdir dir                    # delete an EMPTY directory
ln -s target linkname        # symbolic link
ln target hardlink           # hard link (same inode)
readlink -f link             # resolve a link to a full path
file thing                   # what kind of file is this?
stat thing                   # size, inode, permissions, times

Safe habits: put -- before names that might start with a dash (rm -- "$file"), quote every variable, and use rm -i or ls first when a glob is involved.

Wildcards and expansion

Globbing, Quoting, Order of expansions

Pattern Matches
* any string (not starting with .)
? exactly one character
[abc], [a-f], [!x] one character from a set, a range, or not in the set
{a,b,c}, {1..5}, {01..10} brace expansion (creates words, no matching)
** any depth, after shopt -s globstar

Quoting in one line: 'single' keeps everything literal, "double" still expands $var, $(cmd) and $((1+2)), and an unquoted $var is split into words and globbed, which is the cause of most script bugs.

Finding things

find and locate, grep

Terminal
find . -name '*.log'                    # by name (quote the pattern!)
find . -type f -size +10M               # files over 10 MB
find . -type f -mtime -2                # modified in the last 2 days
find . -type f -name '*.tmp' -delete    # delete matches
find . -type f -print0 | xargs -0 wc -l # safe with odd file names
find . -name '*.sh' -exec chmod +x {} + # run a command on many files

grep -rn 'TODO' src/        # recursive, with line numbers
grep -i -w error app.log    # ignore case, whole word
grep -v '^#' conf           # invert: lines NOT matching
grep -c pattern file        # count matching lines
grep -E 'cat|dog' file      # extended regular expressions
grep -F 'a.b' file          # fixed string, no regex

Text tools

Viewing text, sed, awk, sort, uniq, cut, diff

Terminal
head -n 5 f    tail -n 5 f    tail -f f      # first / last lines / follow
cut -d, -f1,3 f.csv                          # columns 1 and 3 of a CSV
sort -t, -k2,2nr f.csv                       # sort by 2nd column, numeric, reversed
sort file | uniq -c | sort -nr               # frequency table
tr 'a-z' 'A-Z'    tr -d '\r'    tr -s ' '     # translate, delete, squeeze characters
wc -l f   wc -w f   wc -c f                  # lines, words, bytes
sed 's/old/new/g' f                          # replace on every line
sed -n '10,20p' f                            # print lines 10 to 20
sed -i.bak 's/a/b/' f                        # edit in place, keep f.bak (GNU)
awk '{ print $1, $NF }' f                    # first and last field
awk -F: '$3 >= 1000 { print $1 }' /etc/passwd
awk '{ s += $2 } END { print s }' f          # sum a column
diff -u old new                              # unified diff

Redirection and pipes

Streams, Pipes, Here-docs, xargs

Syntax Meaning
cmd > f stdout to file (overwrite)
cmd >> f stdout to file (append)
cmd < f file to stdin
cmd 2> f stderr to file
cmd > f 2>&1 stdout and stderr to the same file (order matters)
cmd &> f the same, Bash shorthand
cmd > /dev/null throw output away
a | b stdout of a is stdin of b
a |& b stdout and stderr of a into b
cmd <<< "text" here-string
cmd <<'EOF' ... EOF here-document (quoted delimiter: no expansion)
<(cmd) process substitution: a command's output as a file name
cmd | tee f show output and save it
Bash Redirection in one place

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Variables and parameter expansion

Variables, Parameter expansion

Form Result
${var:-default} default if var is unset or empty
${var:=default} the same, and also assigns it
${var:?message} abort with message if unset or empty
${#var} length
${var:2:3} substring (offset 2, length 3)
${var#pat} / ${var##pat} remove shortest / longest match from the front
${var%pat} / ${var%%pat} remove shortest / longest match from the end
${var/a/b} / ${var//a/b} replace first / all matches
${var^}, ${var^^}, ${var,,} capitalize, upper-case, lower-case (Bash 4+)
${var@Q} quoted so it can be reused as shell input (Bash 4.4+)
Bash Parameter expansion cheat run

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Tests and conditions

Conditionals, case

Terminal
if [[ -f $file && -r $file ]]; then ...; elif ...; else ...; fi
[[ $answer == y* ]]              # pattern match (right side unquoted)
[[ $s =~ ^[0-9]+$ ]]             # regex match; groups in ${BASH_REMATCH[@]}
(( count > 3 ))                  # arithmetic test, no $ needed inside
cmd1 && cmd2 || cmd3             # and-then / or-else (not a true if/else!)
case $x in a|b) ...;; *.txt) ...;; *) ...;; esac
File tests Meaning String and number tests Meaning
-e exists -z s, -n s empty / not empty
-f, -d, -L regular file, directory, symlink ==, !=, <, > strings
-r, -w, -x readable, writable, executable -eq -ne -lt -le -gt -ge integers
-s exists and is not empty &&, ||, ! and, or, not (inside [[ ]])
Bash File tests and the number versus string trap

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The output shows two surprises worth remembering. -s means "size greater than zero", so a directory counts as non-empty (its own entry takes space on disk), and -f/-e follow a symbolic link, so link is reported as a file as well as a symlink.

Loops, functions and arrays

Loops, Functions, Arrays

Terminal
for f in *.txt; do echo "$f"; done                  # glob (never parse ls)
for ((i = 0; i < 5; i++)); do echo "$i"; done        # C-style
for i in {1..5}; do ...; done                        # brace range
while IFS= read -r line; do echo "$line"; done < file   # lines, safely
until cmd; do sleep 1; done                           # repeat until it succeeds
break; continue                                       # leave / skip an iteration

greet() { local name=${1:-world}; echo "hello $name"; }   # arguments $1 $2 ... $@
result=$(greet Ada)                                       # capture the output
arr=(a b c); arr+=(d); echo "${arr[1]} ${#arr[@]} ${arr[@]}"
for x in "${arr[@]}"; do echo "$x"; done                  # keep elements intact
declare -A age=([ada]=36 [bob]=41); echo "${age[ada]}"    # associative array
for k in "${!age[@]}"; do echo "$k=${age[$k]}"; done      # keys (unordered)

Exit codes and signals

Exit codes and errors, Signals and trap, kill

Code Usual meaning
0 success
1 general error (also "no match" for grep)
2 misuse of a command (bad usage); grep: real error
124 timeout stopped the command
126 / 127 found but not executable / command not found
128+N killed by signal N (130 = Ctrl+C, 137 = SIGKILL, 143 = SIGTERM)
Signal Number Typical use
HUP 1 terminal closed; many daemons reload their config
INT 2 Ctrl+C
QUIT 3 Ctrl+\, quit with core dump
KILL 9 cannot be caught or ignored: last resort
TERM 15 polite request to stop (the default of kill)
USR1, USR2 10, 12 application-defined
STOP, CONT 19, 18 pause and resume (Linux numbers)
Bash Exit statuses, pipefail and timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Processes and jobs

Processes, Jobs

Terminal
ps aux | grep '[n]ginx'       # find a process (the [n] trick hides grep itself)
pgrep -f 'python app.py'      # PIDs by command line
kill PID    kill -9 PID       # ask politely / force
pkill -f pattern              # kill by pattern
cmd &                         # run in the background; $! is its PID
jobs   fg   bg                # job control (interactive shells)
wait                          # wait for all background jobs
nohup cmd &                   # keep running after the terminal closes
timeout 30 cmd                # stop it after 30 seconds

Permissions, archives and the rest

Permissions, Archives, Disk usage

Terminal
chmod 755 script.sh      # rwxr-xr-x     chmod u+x f   chmod -R g-w dir
chmod 644 file.txt       # rw-r--r--
chown user:group file    # change owner (needs root)
umask 022                # new files get 644, new directories 755

tar -czf out.tar.gz dir/       # create a gzip-compressed archive
tar -tzf out.tar.gz            # list it
tar -xzf out.tar.gz -C target/ # extract into target/
sha256sum file > file.sha256   sha256sum -c file.sha256

du -sh dir       du -ah . | sort -h | tail     # sizes
df -h                                          # free space per filesystem

Octal permissions add up as read 4, write 2, execute 1, written for user, group and other: 750 means the owner has rwx, the group r-x, others nothing.

A script skeleton

First script, Arguments, Designing maintainable scripts

Bash A script template with strict mode, usage, trap and options

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

One-liners worth remembering

Text pipelines, Recipes

Bash Ten one-liners on sample data

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which command writes both stdout and stderr of cmd into all.txt?

    Redirections are processed left to right. > all.txt points stdout at the file first, then 2>&1 makes stderr follow stdout. With the order reversed, stderr copies the old stdout (the terminal).
  2. 2. What does ${path%/*} do when path=/var/log/app.log?

    % removes from the end and # from the front. %/* removes the shortest trailing part that matches / plus anything, which is /app.log, leaving the directory part.
  3. 3. What exit status does a command get when it is killed by SIGTERM (signal 15)?

    A process killed by a signal reports 128 plus the signal number, so SIGTERM gives 143 and SIGKILL gives 137.
  4. 4. In for f in *.txt; do rm -- "$f"; done, why are the quotes and -- there?

    Without quotes the shell splits a name like my file.txt into two words. Without --, a file called -rf would be parsed as options by rm.
  5. 5. Why does [[ "5" < "12" ]] evaluate to false?

    Use -lt or (( 5 < 12 )) for numeric comparison. < and > in [[ ]] are string comparisons.

Summary

  • Quote variables, use -- before names that could look like options, and prefer [[ ]] and $(...) in Bash scripts.
  • Redirections are read left to right: > file 2>&1 sends both streams to the file.
  • # and % in parameter expansion trim from the front and the end; doubled, they match as much as possible.
  • Exit status 0 is success; 128+N means killed by signal N; set -o pipefail makes a pipeline fail when any stage fails.
  • find ... -print0 | xargs -0, sort | uniq -c | sort -nr, and awk '!seen[$0]++' cover a large share of everyday text jobs.
  • Start scripts with #!/usr/bin/env bash, set -euo pipefail, a usage function and an EXIT trap for cleanup.

Next: Practice Problems: Commands and Text

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.