Linux Commands

Cheatsheet
File & Directory Operations
Create, Copy, Move, Delete
touch file.txtCreate empty file
mkdir folderCreate directory
mkdir -p a/b/cCreate nested directories
cp file.txt copy.txtCopy file
cp -i file.txt copy.txtCopy with confirmation before overwrite
cp -r folder newfolderCopy directory recursively
mv file.txt newname.txtRename file
mv -i file.txt folder/Move file (interactive overwrite)
rm file.txtDelete file
rm -i file.txtDelete with confirmation
rm -r folderDelete directory recursively
rm -rf folderForce delete (no confirmation, careful!)
rmdir folderDelete empty directory
ln -s /path/to/original /path/to/linkCreate symbolic link
ln file.txt hardlinkCreate hard link
Viewing File Contents
Read files without opening an editor
cat file.txtPrint entire file
cat -n file.txtPrint with line numbers
tac file.txtPrint file in reverse (line order)
less file.txtView file page by page (q to quit)
less -N file.txtView with line numbers
more file.txtSimilar to less, older tool
head file.txtFirst 10 lines
head -n 20 file.txtFirst 20 lines
tail file.txtLast 10 lines
tail -n 20 file.txtLast 20 lines
tail -f file.txtFollow file (live updates, e.g., logs)
wc file.txtWord/line/byte count
wc -l file.txtLine count only
wc -w file.txtWord count only
Searching
Find files and text
Find files by name
find . -name "*.txt"Search current dir recursively
find / -name "file.txt"Search entire filesystem
find . -type d -name "src"Find directories only
find . -type f -mtime -7Files modified in last 7 days
find . -size +100MFiles larger than 100MB
find . -name "*.log" -exec rm {} \;Find and execute command on each result
grep (search text inside files)
grep "search" file.txtSearch for text in file
grep -i "search" file.txtCase-insensitive
grep -r "search" .Recursive search in directory
grep -n "search" file.txtShow line numbers
grep -v "search" file.txtInvert match (lines NOT containing)
grep -c "search" file.txtCount matching lines
grep -l "search" *.txtList filenames matching
grep -L "search" *.txtList filenames NOT matching
grep -E "regex_pattern" file.txtExtended regex
Combine find and grep
find . -name "*.js" | xargs grep "TODO"Search in files matching pattern
find . -type f -exec grep -l "ERROR" {} \;Find files containing "ERROR"
locate / which / whereis
locate file.txtFaster, uses prebuilt index
updatedbUpdate the locate database
which pythonFind command location
whereis pythonFind command, source, and man page
File Permissions
Manage access control
View permissions
ls -l file.txt-rwxr-xr-- format
Change permissions (chmod)
chmod 755 file.txtrwxr-xr-x (owner: all, group/others: read+execute)
chmod 644 file.txtrw-r--r-- (owner: read+write, others: read)
chmod +x script.shAdd execute permission
chmod -x script.shRemove execute permission
chmod u+x file.txtAdd execute for owner (symbolic)
chmod g-w file.txtRemove write for group
chmod o=r file.txtSet read-only for others
chmod -R 755 folderApply recursively
# Permission numbers: 4=read, 2=write, 1=execute (sum them: 7=rwx, 5=r-x, etc.)
Change ownership (chown)
chown user file.txtChange owner
chown user:group file.txtChange owner and group
chown -R user:group folderRecursive change
chgrp group file.txtChange group only
Process Management
Monitor and control running programs
psShow your running processes
ps auxShow all processes (detailed)
ps aux | grep nodeFind specific process
pstreeDisplay process tree
topLive process monitor (q to quit)
htopBetter interactive process monitor
kill PIDTerminate process by ID
kill -9 PIDForce kill
killall firefoxKill by process name
pkill -f "pattern"Kill by matching command
nice -n 10 commandRun command with lower priority
renice 5 -p PIDChange priority of running process
jobsList background jobs
bgResume job in background
fgBring job to foreground
command &Run command in background
nohup command &Run command, survive terminal close
disownDetach job from shell
Disk & System Info
Check system resources
df -hDisk space usage (human-readable)
df -iInode usage
du -h file.txtSize of a file
du -sh folderTotal size of folder
du -sh * | sort -hSize of each item, sorted human-readably
free -hMemory usage (human-readable)
uname -aSystem/kernel info
uptimeSystem uptime and load
whoamiCurrent user
hostnameMachine name
lscpuCPU info
lsblkList block devices/disks
dateCurrent date and time
calDisplay calendar
Networking
Common network commands
ping google.comTest connectivity
ping -c 4 google.comPing 4 times then stop
traceroute google.comTrace route to host
mtr google.comMy traceroute (combines ping and traceroute)
curl https://api.example.comMake HTTP request
curl -X POST -d "data" https://api.example.comPOST request
curl -o file.zip https://example.com/file.zipDownload file
curl -I https://example.comHeaders only
wget https://example.com/file.zipDownload file
wget -c https://example.com/file.zipResume download
ifconfigNetwork interfaces (older)
ip addrNetwork interfaces (modern)
ip aShorthand for ip addr
ip routeShow routing table
netstat -tulpnShow listening ports (older)
ss -tulpnShow listening ports (modern)
nslookup example.comDNS lookup
dig example.comDetailed DNS lookup
ssh user@hostnameConnect via SSH
ssh -i key.pem user@hostnameSSH with key
scp file.txt user@host:/path/Copy file over SSH
scp -r folder user@host:/path/Copy folder over SSH
nc -zv host portCheck if port is open (netcat)
telnet host portConnect to a port (old tool)
hostname -IShow local IP
Archives & Compression
Compress and extract files
tar
tar -cvf archive.tar folder/Create archive
tar -xvf archive.tarExtract archive
tar -czvf archive.tar.gz folder/Create compressed (gzip) archive
tar -xzvf archive.tar.gzExtract .tar.gz
tar -tzvf archive.tar.gzList contents without extracting
tar -xvf archive.tar --wildcards '*.txt'Extract only .txt files
zip / unzip
zip archive.zip file1 file2Create zip
zip -r archive.zip folder/Zip a folder recursively
unzip archive.zipExtract zip
unzip -l archive.zipList contents
gzip / gunzip
gzip file.txtCompress (creates file.txt.gz, removes original)
gunzip file.txt.gzDecompress
gzip -k file.txtCompress but keep original
Package Management
Install software (varies by distro)
Debian/Ubuntu (apt)
sudo apt updateRefresh package list
sudo apt upgradeUpgrade all packages
sudo apt install package_nameInstall package
sudo apt remove package_nameRemove package
sudo apt search package_nameSearch for package
apt list --installedList installed packages
Red Hat/CentOS/Fedora (yum/dnf)
sudo yum install package_nameInstall via yum
sudo dnf install package_nameInstall via dnf
sudo yum list installedList installed (yum)
sudo dnf list installedList installed (dnf)
macOS (Homebrew)
brew install package_nameInstall
brew updateUpdate
brew upgradeUpgrade
brew uninstall package_nameUninstall
brew listList installed
Environment Variables
Manage shell environment
echo $PATHPrint a variable
export VAR_NAME=valueSet variable for current session
envList all environment variables
printenvSame as env
setList all variables (including shell functions)
unset VAR_NAMERemove a variable
# Persist across sessions (add to ~/.bashrc or ~/.zshrc)
export PATH="$PATH:/new/path"Add to PATH
source ~/.bashrcReload shell config
Redirection & Pipes
Control input/output flow
command > file.txtRedirect output to file (overwrite)
command >> file.txtRedirect output to file (append)
command < file.txtUse file as input
command 2> error.txtRedirect errors only
command > out.txt 2>&1Redirect both output and errors
command &> all.txtShorthand for above
command1 | command2Pipe output of command1 into command2
cat file.txt | grep "search" | wc -lChain multiple pipes
command > /dev/nullDiscard output
command > /dev/null 2>&1Discard output and errors
tee file.txtRead from stdin and write to file and stdout
command | tee output.txtSave output while also displaying it
Text Processing
Manipulate text from the command line
sed (stream editor)
sed 's/old/new/' file.txtReplace first occurrence per line
sed 's/old/new/g' file.txtReplace all occurrences
sed -i 's/old/new/g' file.txtEdit file in place
sed -n '2,4p' file.txtPrint lines 2-4
sed -e 's/old/new/' -e 's/foo/bar/' file.txtMultiple edits
awk
awk '{print $1}' file.txtPrint first column
awk -F',' '{print $2}' file.txtUse comma as delimiter
awk '{print NR, $0}' file.txtPrint with line numbers
awk '$3 > 100' file.txtFilter rows by condition
awk 'END {print NR}' file.txtPrint total line count
sort
sort file.txtSort lines alphabetically
sort -n file.txtSort numerically
sort -r file.txtReverse order
sort -u file.txtSort and remove duplicates
sort -k 2 file.txtSort by 2nd column
uniq / cut / tr / diff / paste / join
uniq file.txtRemove duplicate adjacent lines
sort file.txt | uniq -cCount occurrences
cut -d',' -f1 file.txtExtract 1st comma-separated field
cut -c1-5 file.txtExtract characters 1-5
echo "hello" | tr 'a-z' 'A-Z'Convert to uppercase
tr -d '\n' < file.txtRemove newlines
diff file1.txt file2.txtCompare files
diff -u file1.txt file2.txtUnified format (like git diff)
paste file1.txt file2.txtMerge files side by side
join file1.txt file2.txtJoin lines on common field
File Editing (Nano & Vim Basics)
Edit files directly in the terminal
Nano (simple)
nano file.txtOpen in nano
Ctrl+O to save, Ctrl+X to exit, Ctrl+K to cut line, Ctrl+U to paste
Vim (powerful)
vim file.txtOpen in vim
iEnter insert mode
EscExit insert mode (back to normal mode)
:wSave
:qQuit
:wqSave and quit
:q!Quit without saving
ddDelete line
yyCopy (yank) line
pPaste
/searchSearch for text
:%s/old/new/gFind and replace in whole file
System Services (systemd)
Manage background services
sudo systemctl start service_nameStart service
sudo systemctl stop service_nameStop service
sudo systemctl restart service_nameRestart service
sudo systemctl status service_nameCheck status
sudo systemctl enable service_nameEnable on boot
sudo systemctl disable service_nameDisable on boot
systemctl list-units --type=serviceList all services
journalctl -u service_nameView logs for a service
journalctl -fFollow logs live
journalctl --since "1 hour ago"Logs from a time range
User Management
Manage system users
sudo useradd usernameCreate user
sudo passwd usernameSet/change password
sudo userdel usernameDelete user
sudo userdel -r usernameDelete user and home directory
sudo usermod -aG groupname usernameAdd user to group
groups usernameShow user's groups
id usernameShow user/group IDs
su usernameSwitch user
sudo commandRun command as root
sudo -iStart root shell
Aliases & Shell Customization
Speed up common commands
alias ll='ls -la'Create an alias (add to ~/.bashrc or ~/.zshrc for persistence)
alias gs='git status'Git status shortcut
alias ..='cd ..'Go up one directory
unalias llRemove alias
historyShow command history
!123Run command number 123 from history
!!Run last command
Ctrl+RSearch command history interactively
Common Patterns
Frequently used command combinations
find . -name "*.log" -deleteFind and delete files matching pattern
find / -type f -size +100M 2>/dev/nullFind large files
ls -1 | wc -lCount files in directory
watch -n 2 "ls -la"Watch a command run repeatedly (every 2s)
lsof -i :8080Check what's using a port
sudo netstat -tulpn | grep 8080Alternative port check
nohup long_command > output.log 2>&1 &Background a long-running task and log output
command1 && command2Run second only if first succeeds
command1 ; command2Run second regardless
command1 || command2Run second only if first fails
for i in {1..5}; do echo "Run $i"; doneRepeat a command N times
while read line; do echo $line; done < file.txtRead file line by line
if [ -f file.txt ]; then echo "exists"; fiConditional check
cp file.txt file.txt.bakQuickly create a backup
echo $?Check exit status of last command
cat log.txt | grep "ERROR" | grep -v "test"Combine multiple grep filters
ls -la | grep "^-" | wc -lCount number of files (not directories) in current dir