Chapter 02
Shell basics
Moving around, working with files, and how the shell expands patterns, connects commands and finds programs.
Absolute and relative paths
Also called absolute path, relative path, pwd, cd, ls, ~
- What
- An absolute path starts at the root
/; a relative path starts from the current folder.~is your home,.is here and..is the parent.pwdprints where you are,cdmoves andls -lalists everything. - Why
- Every command runs relative to the current folder, so knowing where you are prevents most early accidents.
pwd
ls -la
cd ~/code/app
cd ..
cd - # back to the previous folderWatch out
Running a destructive command without checking pwd first.
File commands
Also called mkdir, cp, mv, rm, touch
- What
mkdir -pcreates folders (and parents),touchcreates an empty file,cp -rcopies,mvmoves or renames,rmdeletes andrm -rdeletes folders.- Why
- They are the basis of every script and every server task.
mkdir -p app/{src,tests,docs}
touch app/README.md
cp -r app app-backup
mv app/README.md app/readme.md
ls app-backup/*.md # preview before deleting
rm -r app-backupWatch out
There is no recycle bin: rm -rf with a typo or an empty variable can delete far more than intended.
Globbing and brace expansion
Also called globbing, glob, wildcards, *, ?
- What
- The shell expands
*(any characters),?(one character) and[abc](one of a set) into matching file names before the command runs. Braces like{a,b}build lists. - Why
- You can act on groups of files in one command, and it explains why a command received a list of names rather than a pattern.
- Example
rm *.tmpis expanded by the shell torm a.tmp b.tmpbefore rm ever runs.
Watch out
A pattern that matches nothing is passed literally in Bash, so the command sees a real *.tmp and fails confusingly.
Quoting
Also called single quotes, double quotes, escaping
- What
- Single quotes keep text exactly as written. Double quotes keep spaces together but still expand
$VARand$(cmd). A backslash escapes one character. - Why
- File names with spaces and variables with unexpected content break commands unless they are quoted.
name="My Notes"
echo '$name' # $name
echo "$name" # My Notes
touch "$name.txt" # one file, not two
ls My\ Notes.txtWatch out
Leaving variables unquoted in scripts, so an empty or spaced value changes the command.
Pipes
Also called |, pipeline
- What
- A pipe
|sends the standard output of one command into the standard input of the next. - Why
- Small single-purpose tools combine into powerful one-liners without temporary files.
history | grep git | tail -5
ls *.md | wc -l
ps aux | grep nodeWatch out
Writing the whole pipeline at once; build it one step at a time and check each output.
Redirection and the three streams
Also called standard input, standard output, standard error, stdin, stdout, stderr, >>, 2>&1
- What
- Programs read standard input and write standard output and standard error.
>writes output to a file,>>appends,<reads from a file,2>redirects errors and2>&1merges errors into output. - Why
- You can save results, keep logs, silence noise with
/dev/nulland still see errors on screen.
ls > files.txt
date >> log.txt
npm test > out.log 2> err.log
./backup.sh >> backup.log 2>&1
cmd > /dev/null 2>&1Watch out
Using > where you meant >>, which empties the file first.
Environment variables
Also called export, env
- What
- Named values inherited by every program the shell starts, such as
HOME,USER,EDITORandPATH.exportmakes a variable visible to child programs. - Why
- Tools read configuration and secrets from them without hard-coding values into code.
echo "$HOME"
env | sort | less
export API_URL="http://localhost:3000"
NODE_ENV=test npm test # for one command only
unset API_URLWatch out
Expecting a variable set in one tab to exist in another, or after closing the terminal.
PATH
Also called PATH variable, command not found, which, type
- What
- A colon-separated list of folders the shell searches, in order, for commands. The first match wins.
- Why
- "Command not found" and "wrong version runs" are almost always PATH problems.
echo "$PATH" | tr ':' '\n'
which python3
type -a node
export PATH="$HOME/.local/bin:$PATH"Watch out
Adding the same PATH line to several startup files until nobody knows which one applies.
Shell startup files and aliases
Also called shell startup file, startup file, shell profile, .bashrc, .zshrc, .profile, alias
- What
- Files the shell runs when it starts:
~/.bashrcfor interactive Bash,~/.zshrcfor zsh, and login files such as~/.profileor~/.zprofile. Aliases and small functions live there too. - Why
- PATH changes, exports and shortcuts you add there apply to every new terminal.
# in ~/.bashrc or ~/.zshrc
export EDITOR="nano"
alias gs="git status"
alias ll="ls -la"
mkcd() { mkdir -p "$1" && cd "$1"; }
source ~/.bashrc # reload without a new tabWatch out
Editing .bashrc while your shell is zsh, then wondering why nothing changed.
nano and Vim
Also called Vim, nano, vi, vimtutor, terminal editor
- What
- Terminal editors. nano shows its shortcuts: Ctrl+O saves, Ctrl+X exits. Vim is modal:
ito insert, Esc for normal mode,:wqto save and quit,:q!to quit without saving. - Why
- Servers often have no graphical editor, and Git opens an editor for merges and some commits.
- Example
- Run
vimtutorfor a guided 30-minute Vim lesson.
Watch out
Getting stuck in Vim; press Esc, then type :q! and Enter.
Opening files and the clipboard
Also called File Explorer, open, xdg-open, explorer.exe, pbcopy
- What
- Commands that hand a file to your desktop or move text to and from the clipboard. They differ by operating system.
- Why
- Opening a folder or copying a command's output without the mouse keeps you in the terminal.
explorer.exe . # open folder in File Explorer
cat key.pub | clip.exe # copy to Windows clipboard
powershell.exe Get-Clipboard # paste
wslview report.html # if wslu is installed