Skip to content

Thủ thuật Terminal (Zsh/Bash) 💻

Terminal nhanh hơn bất kỳ GUI nào. Làm chủ nó.

Tip 1: Aliases - Shortcut Everything

Problem

Gõ đi gõ lại những lệnh dài và phức tạp hàng chục lần mỗi ngày.

Solution

Tạo aliases để rút ngắn lệnh thành 2-3 ký tự.

Example

Thêm vào ~/.zshrc hoặc ~/.bashrc:

bash
# Git shortcuts
alias gs='git status'
alias ga='git add'
alias gc='git commit -m'
alias gp='git push'
alias gl='git log --oneline --graph --all'
alias gd='git diff'

# Navigation
alias ..='cd ..'
alias ...='cd ../..'
alias ~='cd ~'

# List files
alias ll='ls -lah'
alias la='ls -A'

# Safety nets
alias rm='rm -i'  # Confirm before delete
alias cp='cp -i'  # Confirm before overwrite
alias mv='mv -i'  # Confirm before overwrite

# Project shortcuts
alias dev='cd ~/projects && code .'
alias serve='python -m http.server 8000'

Usage: gs thay vì git status

Pro Tips

  • Reload config: source ~/.zshrc
  • List all aliases: alias
  • Temporary bypass alias: \rm file.txt (skip confirmation)

Tip 2: Reverse History Search với Ctrl + R

Problem

Bạn đã chạy một lệnh phức tạp 2 tuần trước, không nhớ chính xác.

Solution

Ctrl + R: Reverse search trong command history.

Example

bash
# Nhấn Ctrl + R
(reverse-i-search)`': 

# Gõ "docker"
(reverse-i-search)`docker': docker run -p 8080:80 nginx

# Nhấn Enter để chạy, hoặc Ctrl + R tiếp để xem lệnh cũ hơn

Pro Tips

  • Ctrl + R nhiều lần: Duyệt qua các kết quả
  • Ctrl + G: Cancel search
  • Ctrl + S: Forward search (cần stty -ixon trong .zshrc)
  • Tăng history size: HISTSIZE=10000 trong config

Tip 3: Command Chaining với && và ||

Problem

Chạy nhiều lệnh tuần tự, nhưng muốn dừng nếu có lỗi.

Solution

  • &&: Chạy lệnh thứ 2 CHỈ KHI lệnh đầu thành công
  • ||: Chạy lệnh thứ 2 CHỈ KHI lệnh đầu thất bại
  • ;: Chạy lệnh thứ 2 bất kể lệnh đầu thế nào

Example

bash
# Good: Chỉ cd nếu mkdir thành công
mkdir project && cd project

# Good: Fallback nếu command thất bại
npm start || echo "Failed to start server"

# Bad: cd vào directory không tồn tại
mkdir project ; cd project  # cd chạy dù mkdir fail!

# Chain nhiều lệnh
git pull && npm install && npm run build && npm test

Pro Tips

  • Exit code: $? (0 = success, non-zero = failure)
  • Check last command: echo $?
  • Combine: cmd1 && cmd2 || cmd3 (if cmd1 success run cmd2, else run cmd3)

Tip 4: Pipes (|) - Chain Command Outputs

Problem

Cần xử lý output của một lệnh bằng lệnh khác.

Solution

| (pipe): Truyền output của lệnh này sang input của lệnh khác.

Example

bash
# Tìm lỗi trong log file khổng lồ
cat app.log | grep "ERROR"

# Đếm số lỗi
cat app.log | grep "ERROR" | wc -l

# Tìm process đang chạy
ps aux | grep "node"

# Xem 10 files lớn nhất
du -sh * | sort -rh | head -10

# Real-time log monitoring
tail -f app.log | grep --line-buffered "ERROR"

Pro Tips

  • tee: Pipe và save to file cùng lúc: cmd | tee output.txt
  • xargs: Convert stdin thành arguments: find . -name "*.log" | xargs rm
  • Combine với awk, sed cho text processing mạnh mẽ

Tip 5: Background Jobs với & và fg/bg

Problem

Chạy lệnh lâu (build, server) block terminal.

Solution

  • &: Chạy lệnh ở background
  • Ctrl + Z: Suspend lệnh đang chạy
  • bg: Resume lệnh ở background
  • fg: Bring lệnh về foreground
  • jobs: List background jobs

Example

bash
# Chạy server ở background
npm run dev &

# Suspend lệnh đang chạy
npm run build
# Nhấn Ctrl + Z
[1]+  Stopped    npm run build

# Resume ở background
bg

# List jobs
jobs
[1]+  Running    npm run build &

# Bring về foreground
fg %1

Pro Tips

  • Kill background job: kill %1
  • Disown job (chạy sau khi đóng terminal): disown %1
  • Better: Dùng tmux hoặc screen cho session management

Tip 6: Find Files với find và fd

Problem

Tìm file trong project lớn mất thời gian.

Solution

find (built-in) hoặc fd (modern alternative).

Example

bash
# Find by name
find . -name "*.js"

# Find and delete
find . -name "node_modules" -type d -exec rm -rf {} +

# Find files modified in last 7 days
find . -mtime -7

# fd (faster, better syntax)
fd "\.js$"
fd --type f --extension js
fd --hidden --no-ignore  # Include hidden and gitignored files

Pro Tips

  • Install fd: brew install fd (Mac) hoặc apt install fd-find (Linux)
  • Combine với xargs: fd "\.log$" | xargs rm
  • Exclude directories: fd --exclude node_modules

Tip 7: Search Content với grep và ripgrep

Problem

Tìm text trong nhiều files.

Solution

grep (built-in) hoặc ripgrep (rg - faster).

Example

bash
# grep: Search in files
grep -r "TODO" .
grep -rn "function" src/  # -n: show line numbers
grep -ri "error" logs/    # -i: case insensitive

# ripgrep (rg): Much faster
rg "TODO"
rg "function" src/
rg -i "error" logs/
rg --type js "import"  # Only search .js files

Pro Tips

  • Install ripgrep: brew install ripgrep hoặc apt install ripgrep
  • Exclude files: rg --glob '!node_modules' "TODO"
  • Show context: rg -C 3 "error" (3 lines before/after)
  • Count matches: rg -c "TODO"

Tip 8: Directory Navigation với z/autojump

Problem

cd vào deep directories mất thời gian: cd ~/projects/work/client/frontend/src/components

Solution

z hoặc autojump: Jump to frequently used directories.

Example

bash
# Install z (for zsh)
# Add to ~/.zshrc: source /path/to/z.sh

# After visiting directories a few times
cd ~/projects/work/client/frontend/src/components
cd ~/projects/personal/blog

# Later, jump instantly
z components  # → ~/projects/work/client/frontend/src/components
z blog        # → ~/projects/personal/blog

# Fuzzy matching
z comp  # → components directory

Pro Tips

  • z -l: List all tracked directories
  • z -c: Restrict to subdirectories of current directory
  • Alternative: autojump (similar functionality)
  • Zsh built-in: setopt AUTO_CD (type directory name to cd)

Tip 9: Command Substitution với $()

Problem

Cần dùng output của một lệnh làm argument cho lệnh khác.

Solution

$(command): Execute command và thay thế bằng output.

Example

bash
# Get current date in filename
cp app.log app-$(date +%Y%m%d).log

# Count files in directory
echo "Total files: $(ls | wc -l)"

# Backup with timestamp
tar -czf backup-$(date +%Y%m%d-%H%M%S).tar.gz src/

# Kill process by name
kill $(ps aux | grep "node" | awk '{print $2}')

# Git: Checkout branch from list
git checkout $(git branch | fzf)

Pro Tips

  • Old syntax: `command` (backticks) - avoid, use $()
  • Nested: echo $(echo $(date))
  • Combine với pipes: echo $(cat file.txt | grep "error")

Tip 10: Terminal Multiplexer với tmux

Problem

  • Cần nhiều terminal windows
  • SSH session bị disconnect mất hết công việc
  • Muốn share terminal session với teammate

Solution

tmux: Terminal multiplexer - multiple terminals trong một window.

Example

bash
# Install
brew install tmux  # Mac
apt install tmux   # Linux

# Start new session
tmux

# Basic commands (prefix: Ctrl + B)
Ctrl + B, C        # Create new window
Ctrl + B, N        # Next window
Ctrl + B, P        # Previous window
Ctrl + B, %        # Split vertically
Ctrl + B, "        # Split horizontally
Ctrl + B, Arrow    # Navigate panes
Ctrl + B, D        # Detach session

# Reattach session
tmux attach

# List sessions
tmux ls

# Named sessions
tmux new -s work
tmux attach -t work

Pro Tips

  • Sessions survive SSH disconnects
  • Share session: tmux attach -t work (multiple users)
  • Customize: ~/.tmux.conf
  • Alternative: screen (older, less features)
  • Plugin manager: tpm (Tmux Plugin Manager)

📋 Quick Reference

CommandActionUse Case
aliasCreate shortcutsSpeed up common commands
Ctrl + RReverse searchFind old commands
&&Chain commandsRun if previous succeeds
|Pipe outputProcess command output
&Background jobRun without blocking
find / fdFind filesLocate files by name
grep / rgSearch contentFind text in files
zJump to directoryNavigate faster
$()Command substitutionUse output as argument
tmuxTerminal multiplexerMultiple terminals

🎯 Luyện tập ngay