Linux Command Line Basics for Developers
The shell commands you use every day: navigation, files, search, pipes, permissions, and the habits that make the terminal fast.
By Velloreth
Navigation
pwd # print working directory
ls -la # list all, long format
cd /var/log # change directory
cd - # back to the previous directory
cd ~ # home
Useful ls flags: -l long, -a include hidden, -h human-readable sizes, -t sort by time, -S sort by size.
Files and directories
touch file.txt # create empty file
mkdir -p a/b/c # create nested directories
cp -r src/ dest/ # copy recursively
mv old.txt new.txt # move or rename
rm file.txt # remove
rm -rf dir/ # remove recursively (careful)
ln -s /path/to/target link # symbolic link
rm -rf is irreversible. There is no trash. Check the path before running it, especially with a variable in it.
Viewing files
cat file.txt # print the whole file
less file.txt # page through it
head -20 file.txt # first 20 lines
tail -20 file.txt # last 20 lines
tail -f app.log # follow a growing file
wc -l file.txt # count lines
less is the right tool for a large file: it does not load the whole thing, and it supports search with /.
Searching
grep searches file contents.
grep "error" app.log
grep -i "error" app.log # case-insensitive
grep -r "TODO" src/ # recursive
grep -rn "TODO" src/ # with line numbers
grep -l "TODO" src/*.js # filenames only
grep -v "debug" app.log # invert: lines that do not match
grep -c "error" app.log # count matches
grep -E "err(or|ors)" app.log # extended regex
find searches the filesystem.
find . -name "*.js"
find . -type f -name "*.log"
find . -type d -name node_modules
find . -mtime -7 # modified in the last 7 days
find . -size +100M # larger than 100MB
find . -name "*.tmp" -delete # find and delete
find . -name "*.js" -exec wc -l {} +
-exec with + batches the arguments, which is much faster than \; which runs the command once per file.
Pipes and redirection
ls -la | grep ".log" # pipe output to grep
cat file.txt | wc -l # count lines
ps aux | grep node # find a process
command > out.txt # redirect, overwrite
command >> out.txt # redirect, append
command 2> err.txt # redirect stderr
command > out.txt 2>&1 # both to the same file
command | tee out.txt # write and display
tee is useful when you want to see the output and save it.
2>&1 redirects stderr to wherever stdout is going. The order matters: > file 2>&1 works, 2>&1 > file does not.
Text processing
sed edits a stream.
sed 's/old/new/' file.txt # replace first per line
sed 's/old/new/g' file.txt # replace all
sed -i 's/old/new/g' file.txt # edit in place
sed -n '10,20p' file.txt # print lines 10-20
sed '/pattern/d' file.txt # delete matching lines
awk processes columns.
awk '{print $1}' file.txt # first column
awk -F: '{print $1}' /etc/passwd # custom delimiter
awk '$3 > 100' file.txt # filter by a column
awk '{sum += $1} END {print sum}' file.txt
cut extracts columns.
cut -d: -f1 /etc/passwd
cut -c1-10 file.txt
sort and uniq are a classic pair.
sort file.txt | uniq # deduplicate adjacent
sort file.txt | uniq -c # count occurrences
sort -rn numbers.txt # numeric, reverse
sort -u file.txt # sort and deduplicate
uniq only removes adjacent duplicates, which is why it is almost always preceded by sort.
Permissions
chmod 755 script.sh
chmod +x script.sh
chown user:group file.txt
The digits are read (4), write (2), and execute (1), summed for owner, group, and others.
| Mode | Meaning |
|---|---|
| 644 | Owner read-write, others read |
| 755 | Owner read-write-execute, others read-execute |
| 600 | Owner read-write only |
| 700 | Owner read-write-execute only |
sudo runs a command as root. Use it sparingly, and never with a command you do not understand.
Processes
ps aux # all processes
ps aux | grep node # find one
top # live view
htop # better live view
kill 1234 # terminate by PID
kill -9 1234 # force
pkill -f "node server" # by pattern
jobs # background jobs
fg # bring to foreground
kill -9 cannot be caught, so the process cannot clean up. Try a plain kill first.
Networking
curl -I https://example.com # headers only
curl -X POST -d '{"a":1}' url # POST with a body
curl -o file.zip url # save to a file
wget url # download
ss -tulpn # listening ports
ping example.com
dig example.com
Archives
tar -czf archive.tar.gz dir/ # create
tar -xzf archive.tar.gz # extract
tar -tzf archive.tar.gz # list contents
zip -r archive.zip dir/
unzip archive.zip
The flags: c create, x extract, t list, z gzip, f file, v verbose.
Shell shortcuts
| Shortcut | Action |
|---|---|
Tab | Complete a path or command |
Ctrl+R | Search history |
Ctrl+C | Cancel the current command |
Ctrl+D | End input / exit |
Ctrl+L | Clear the screen |
Ctrl+A | Start of line |
Ctrl+E | End of line |
Ctrl+U | Delete to start of line |
Ctrl+W | Delete the previous word |
!! | Repeat the last command |
!$ | Last argument of the previous command |
Ctrl+R is the one worth learning first: it searches your command history as you type.
Environment and PATH
The shell finds a command by searching the directories in PATH.
echo $PATH
which node
type node
type is more informative than which: it reports whether the name is a builtin, an alias, a function, or an executable, and where it resolves.
Add a directory to PATH:
export PATH="$HOME/.local/bin:$PATH"
Put it in ~/.bashrc or ~/.zshrc to make it permanent. The order matters: an earlier directory wins.
Environment variables:
export EDITOR=nvim
printenv | sort
env | grep NODE
A variable for one command:
NODE_ENV=production node server.js
Aliases and functions
An alias is a shortcut for a command.
alias ll='ls -lah'
alias gs='git status -sb'
alias ..='cd ..'
Put them in ~/.bashrc. A function is more powerful, because it can take arguments.
mkcd() {
mkdir -p "$1" && cd "$1"
}
gclean() {
git branch --merged | grep -v '\*' | xargs -r git branch -d
}
alias does not take arguments in the way a function does, which is the main reason to prefer a function.
Job control
long-command & # run in the background
jobs # list background jobs
fg %1 # bring job 1 to the foreground
bg %1 # resume job 1 in the background
Ctrl+Z # suspend the foreground job
disown %1 # detach from the shell
nohup command & # survive the shell exiting
nohup is the classic way to run a command that outlives the terminal. For a long-running service, a process manager or a container is a better answer.
Disk and system
df -h # disk usage by filesystem
du -sh dir/ # size of a directory
du -h --max-depth=1 . # sizes of subdirectories
free -h # memory
uptime # load average
uname -a # kernel and architecture
lsblk # block devices
du -h --max-depth=1 is the fastest way to find what is filling a disk: it shows the size of each subdirectory at one level.
df -h versus du -sh. df reports the filesystem’s usage, and du reports the total size of the files. They can disagree when a deleted file is still held open by a process, which is a classic cause of a full disk that du cannot explain.
Finding what is using a port
ss -tulpn | grep :3000
lsof -i :3000
fuser 3000/tcp
lsof -i :3000 shows the process holding the port, which is the answer to “address already in use”.
Comparing and diffing
diff file1.txt file2.txt
diff -u file1.txt file2.txt # unified format
diff -r dir1/ dir2/ # recursive
comm -12 <(sort a.txt) <(sort b.txt) # lines in both
comm -23 <(sort a.txt) <(sort b.txt) # lines only in a
Process substitution with <(command) treats a command’s output as a file, which is how comm and diff are used with sorted input.
Text editors in the terminal
nano is the simplest: the shortcuts are shown at the bottom, and Ctrl+O saves and Ctrl+X exits.
vim is modal: i enters insert mode, Esc returns to normal mode, :w saves, and :q exits. :wq does both.
A quick edit without an editor:
sed -i 's/old/new/g' file.txt
Set the default editor:
export EDITOR=nvim
This is what git commit and crontab -e use.
Getting help
man ls # the manual page
ls --help # a quick summary
man -k "search" # search the manuals
apropos "copy file" # find a command by description
tldr tar # practical examples
tldr is worth installing: it shows the common examples rather than the full manual, which is usually what you want.
man navigation: / searches, n goes to the next match, and q quits.
Working with remote machines
The command line is how you reach a server, and a few habits make that safer. Before running a destructive command, print the variable you are about to use, so you can see the actual value rather than the one you intended. Use set -u in a script so an unset variable is an error rather than an empty string, which is how a rm -rf "$DIR/" becomes a rm -rf /. Prefer a dry run where the tool offers one, and prefer a reversible operation where it does not. When you are connected to a production machine, slow down: the commands are the same, but the consequences are not, and there is no undo. Keeping a second session open is a useful safety net, because a mistake that breaks your connection does not lock you out entirely.
Building a mental model
The shell rewards a mental model more than a memorised list. Every command reads from standard input and writes to standard output and standard error, which is why pipes and redirection compose so freely. A command that seems to do something surprising is usually doing exactly what it says, and the surprise comes from an assumption about the input. When a pipeline misbehaves, run it one stage at a time and look at the output of each, rather than guessing at the whole. The same applies to a script: bash -x prints each command with its expanded arguments, which turns a mystery into a sequence you can read. The tools are small and predictable, and the skill is in combining them.
Practical guidance
- Use
lessfor large files, notcat. - Use
grep -rnto search a codebase. - Use
find -exec ... +rather than\;. - Remember
uniqneedssortfirst. - Use
teeto see and save output. - Learn
Ctrl+Rfor history search. - Be careful with
rm -rfand a variable in the path. - Use
nginx -t-style validation before destructive commands.
For the related guides, see bash-scripting-basics and ssh-and-keys-guide. For the broader context, environment-variables-explained and cron-expressions-explained.
Quotable summary
Everything in Linux is a file, and the shell is a language for combining small tools, with pipes connecting the output of one command to the input of the next. grep, find, sed, and awk cover most text processing, and uniq only removes adjacent duplicates, which is why it is almost always preceded by sort. Permissions are read, write, and execute for owner, group, and others, so 755 is read-write-execute for the owner and read-execute for everyone else. Learn the shortcuts — Ctrl+R for history search, Ctrl+C to cancel, and Tab for completion — and be careful with rm -rf, which is irreversible and has no trash.