Shell進階筆記 - The Missing Semester of Your CS Education
Shell Scripting
Variables:
- Assign:
foo=bar - Access:
$foo - Note: No spaces around
=in assignment.
- Assign:
Strings:
- Single quotes (
') → Literal string (no variable substitution). - Double quotes (
") → Variable substitution.
- Single quotes (
Special Variables:
$0→ Script name.$1to$9→ Script arguments.$@→ All arguments.$#→ Number of arguments.$?→ Return code of the last command.$$→ Current script PID.!!→ Last command (useful forsudo !!).$_→ Last argument of the last command.can run like this
echo $?
Control Flow:
if,case,while,forconstructs.Example function:
mcd () { mkdir -p "$1" cd "$1" }
Exit Codes & Operators:
0→ Success, non-zero → Error.&&(AND),||(OR),;(sequential execution).Examples:
false || echo "Oops, fail" # Oops, fail true && echo "Success" # Success
Command & Process Substitution:
$(CMD)→ Substitute command output.<(CMD)→ Process substitution (temporary file).
Globbing:
Wildcards:
?(single char),*(any chars).Curly braces
{}for expansion:convert image.{png,jpg} → convert image.png image.jpg
Shebang:
#!/usr/bin/env python→ Portable script execution.
Scripts vs. Functions:
- Scripts run in their own process; functions modify the current shell.
Shell Tools
Finding Commands:
CMD -hor--help→ Quick help.man CMD→ Full manual.tldr CMD→ Simplified examples.
Finding Files:
find:find . -name "*.txt" -type f find . -mtime -1 # Modified in last day find . -size +1M # Files >1MB find . -exec rm {} \; # Delete matchesAlternatives:
fd PATTERN→ Faster, user-friendly.locate FILE→ Uses pre-built database.
Finding Code:
grep:grep -R "pattern" . # Recursive search grep -C 5 "pattern" # Context (5 lines around match)Alternatives:
rg(ripgrep),ag,ack.
Finding Shell Commands:
history | grep CMD→ Search past commands.Ctrl+R→ Reverse search.fzf→ Fuzzy history search.
Directory Navigation:
z DIR(fasd) /j DIR(autojump) → Quick directory jumps.- Tools:
tree,broot,nnn,ranger.
Key Commands Summary
| Category | Commands/Tools |
|---|---|
| Variables | foo=bar, $foo, $1-$9, $? |
| Strings | 'literal', "substitute $var" |
| Control | if, for, while, &&, || |
| Substitution | $(CMD), <(CMD) |
| Globbing | *, ?, {} |
| Finding | find, fd, grep, rg, locate |
| History | history, Ctrl+R, fzf |
| Navigation | z, j, tree, ranger |