← Home

Bash/Shell Commands Cheatsheet

Every essential command-line tool in one place — file management, text processing, networking, scripting, and more. Bookmark this page and never Google a command again.

File System

CommandDescription
ls -laList all files including hidden, with details (permissions, size, date)
ls -lhSList files sorted by size, human-readable
cd ~/projectsChange directory — use ~, -, .., or absolute paths
pwdPrint the current working directory
mkdir -p a/b/cCreate nested directories, no error if they exist
rmdir dirRemove an empty directory
rm -rf dir/Recursively remove directory and all contents (use with caution)
rm -i file.txtRemove file with interactive confirmation prompt
cp -r src/ dest/Copy files or directories recursively
cp -a src/ dest/Archive copy — preserves permissions, symlinks, timestamps
mv old.txt new.txtMove or rename files and directories
touch file.txtCreate an empty file or update its timestamp
find . -name '*.log'Find files by name pattern recursively
find . -type f -mtime -7Find files modified in the last 7 days
find . -size +100MFind files larger than 100 MB
du -sh */Show disk usage summary per subdirectory, human-readable
df -hShow free disk space on all mounted filesystems
ln -s target linkCreate a symbolic link
stat file.txtDisplay detailed file metadata (size, inode, timestamps)
tree -L 2Show directory tree limited to 2 levels deep

File Content

CommandDescription
cat file.txtPrint entire file contents to stdout
cat -n file.txtPrint file with line numbers
less file.txtPaginated viewer — navigate with j/k, search with /, quit with q
more file.txtSimple forward-only pager (spacebar to scroll)
head -n 20 file.txtPrint the first 20 lines of a file
tail -n 50 file.txtPrint the last 50 lines of a file
tail -f app.logFollow a file in real time (great for logs)
grep -rn 'pattern' .Search recursively with line numbers
grep -i 'error' log.txtCase-insensitive search in a file
grep -v 'debug' log.txtInvert match — show lines NOT containing pattern
grep -E 'err|warn' log.txtExtended regex — match multiple patterns
sed 's/old/new/g' fileReplace all occurrences of old with new
sed -i '' 's/old/new/g' fIn-place replacement (macOS syntax)
sed -n '10,20p' filePrint only lines 10 through 20
awk '{print $1, $3}' filePrint the 1st and 3rd whitespace-delimited columns
awk -F: '{print $1}' /etc/passwdUse : as field separator, print first field
wc -l file.txtCount lines in a file (-w for words, -c for bytes)
sort file.txtSort lines alphabetically (-n for numeric, -r for reverse)
sort -t, -k2 -n data.csvSort CSV by 2nd column numerically
uniq -cDeduplicate consecutive lines and show counts
cut -d',' -f1,3 data.csvExtract 1st and 3rd comma-delimited fields
tr 'a-z' 'A-Z'Translate (transform) lowercase to uppercase
tr -d '\n'Delete all newlines from input
tee output.logRead stdin, write to both stdout and a file

Permissions & Ownership

CommandDescription
chmod 755 script.shOwner rwx, group rx, others rx (common for scripts)
chmod 644 file.txtOwner rw, group r, others r (common for files)
chmod +x script.shAdd execute permission for all users
chmod -R 750 dir/Recursively set permissions on a directory
chmod u+rw,go-w fileSymbolic: add rw for user, remove write for group/others
chown user:group fileChange file owner and group
chown -R user dir/Recursively change ownership of a directory
chgrp staff file.txtChange group ownership of a file
umask 022Set default permission mask (new files get 644, dirs 755)
umaskDisplay current umask value
ls -laView permissions as rwxrwxrwx alongside owner and group
stat -f '%Sp %Su %Sg' fileShow permissions, owner, group (macOS)

Process Management

CommandDescription
ps auxList all running processes with details
ps aux | grep nodeFind processes matching a name
topReal-time process monitor (q to quit)
htopInteractive process viewer with color and mouse support
kill PIDSend SIGTERM (graceful stop) to a process by PID
kill -9 PIDSend SIGKILL (force kill) — use as last resort
killall nodeKill all processes matching a name
pkill -f 'python app'Kill processes matching a full command string
jobsList background jobs in the current shell
bg %1Resume stopped job #1 in the background
fg %1Bring background job #1 to the foreground
nohup ./run.sh &Run command immune to hangups, persists after logout
cmd &Run command in the background
waitWait for all background jobs to finish
lsof -i :3000Find which process is using port 3000
xargs -P 4Run up to 4 parallel processes from stdin

Networking

CommandDescription
curl https://api.example.comFetch URL content to stdout
curl -o file.zip URLDownload file from URL, save with given name
curl -X POST -d '{...}' URLSend POST request with data payload
curl -H 'Auth: token' URLSend request with custom header
curl -sS URL | jq .Fetch JSON silently and pretty-print with jq
wget -c URLDownload file with resume support on interruption
wget -r -l 2 URLRecursively download up to 2 levels deep
ping -c 4 google.comSend 4 ICMP echo requests to test connectivity
ssh user@hostOpen secure shell connection to remote server
ssh -L 8080:localhost:80 hostLocal port forwarding (tunnel)
scp file.txt user@host:~/Securely copy file to remote server
scp -r dir/ user@host:~/Securely copy directory recursively
rsync -avz src/ host:dest/Sync files efficiently — only transfers diffs
rsync --delete src/ dest/Sync and delete files in dest not in src
netstat -tulpnShow listening ports and associated processes
ss -tulpnModern replacement for netstat — faster, more info
ip addr showDisplay network interfaces and IP addresses
dig example.comDNS lookup — query name servers for DNS records
nslookup example.comSimple DNS query for IP resolution
traceroute google.comTrace the network path to a destination

Archive & Compression

CommandDescription
tar -czf archive.tar.gz dir/Create gzip-compressed tar archive
tar -xzf archive.tar.gzExtract gzip-compressed tar archive
tar -xzf archive.tar.gz -C dest/Extract to a specific directory
tar -tf archive.tar.gzList contents of a tar archive without extracting
tar -cjf archive.tar.bz2 dir/Create bzip2-compressed tar archive
gzip file.txtCompress file in-place (produces file.txt.gz)
gunzip file.txt.gzDecompress gzip file in-place
gzip -k file.txtCompress and keep the original file
zip -r archive.zip dir/Create zip archive of a directory
unzip archive.zip -d dest/Extract zip to a specific directory
unzip -l archive.zipList contents of a zip archive
xz file.txtCompress with xz (high compression ratio)
xz -d file.txt.xzDecompress xz file
zcat file.gzView contents of gzipped file without extracting

System Info

CommandDescription
uname -aPrint all system information (kernel, arch, hostname)
uname -rPrint kernel release version
whoamiPrint the current username
idPrint user ID, group ID, and group memberships
hostnamePrint or set the system hostname
datePrint current date and time
date +%Y-%m-%dPrint date in YYYY-MM-DD format
uptimeShow how long the system has been running
free -hDisplay memory usage (total, used, free) human-readable
lsb_release -aPrint Linux distribution information
cat /etc/os-releaseDisplay OS name, version, and ID
envPrint all environment variables
printenv PATHPrint a specific environment variable
which nodeShow the full path of a command binary
type lsShow whether a command is an alias, builtin, or file
alias ll='ls -la'Create a shorthand alias for a command

Text Processing

CommandDescription
echo 'Hello World'Print text to stdout
echo -e '\t indented'Print with escape sequences (tabs, newlines)
printf '%-10s %d\n' name 42Formatted output with padding and types
xargs -I {} cmd {}Build and execute commands from stdin items
xargs -n 1 echoExecute command once per input line
tee >(grep err > errs.log)Tee into process substitution for filtering
diff file1 file2Show line-by-line differences between two files
diff -u file1 file2Unified diff format (common in patches)
diff -rq dir1/ dir2/Recursively compare directories, report only diffs
comm file1 file2Compare two sorted files line by line (3 columns)
paste file1 file2Merge lines from two files side by side
paste -sd, file.txtJoin all lines into one line with comma separator
column -t -s, data.csvFormat CSV into aligned columns
revReverse each line of input character by character
nl file.txtNumber all non-empty lines in a file
expand -t 4 file.txtConvert tabs to 4 spaces

Shell Features & Scripting

CommandDescription
cmd1 | cmd2Pipe — send stdout of cmd1 to stdin of cmd2
cmd > file.txtRedirect stdout to file (overwrite)
cmd >> file.txtRedirect stdout to file (append)
cmd < input.txtRedirect file as stdin to a command
cmd 2> errors.logRedirect stderr only to a file
cmd &> all.logRedirect both stdout and stderr to a file
cmd 2>&1 | tee log.txtMerge stderr into stdout and tee to file
$(command)Command substitution — capture output as a string
VAR=valueSet a shell variable (no spaces around =)
export VAR=valueSet and export variable to child processes
$HOME, $USER, $PWD, $?Common variables — home dir, user, cwd, last exit code
"$VAR" vs '$VAR'Double quotes expand variables, single quotes are literal
if [ -f file ]; then ... fiConditional — check if file exists
[ -d dir ] && echo yesShort-circuit — run echo only if dir exists
for f in *.txt; do ... doneLoop over files matching a glob
while read -r line; do ... done < fRead a file line by line in a loop
cmd1 && cmd2Run cmd2 only if cmd1 succeeds (exit code 0)
cmd1 || cmd2Run cmd2 only if cmd1 fails (non-zero exit)
{ cmd1; cmd2; } > out.txtGroup commands and redirect combined output
history | grep sshSearch command history for past commands
!!Re-run the last command
sudo !!Re-run the last command with sudo
set -euo pipefailStrict mode — exit on error, unset var, or pipe fail
#!/usr/bin/env bashPortable shebang line for Bash scripts

FAQ

What is the difference between Bash and Shell?

A "shell" is any command-line interpreter (sh, bash, zsh, fish, etc.). Bash (Bourne Again SHell) is the most common shell on Linux and older macOS. macOS now defaults to Zsh, which is largely Bash-compatible. Most commands on this page work in any POSIX-compatible shell.

How do I make a Bash script executable?

Add a shebang line (#!/usr/bin/env bash) as the first line of your script, then run chmod +x script.sh. You can then execute it with ./script.sh. The shebang tells the OS which interpreter to use.

What does set -euo pipefail do and should I use it?

It enables strict mode: -e exits on any error, -u treats unset variables as errors, -o pipefail makes pipes fail if any command in the chain fails. It's strongly recommended at the top of every Bash script to catch bugs early instead of silently continuing after failures.

How can I chain multiple commands together?

Use && to run the next command only if the previous succeeds, || to run only if it fails, ; to run regardless of success, and | (pipe) to feed one command's output into another. For example: mkdir build && cd build && cmake .. runs each step only if the previous one worked.

Related Resources