
Your complete reference guide to essential Linux commands — from file operations and process management to networking, scripting, and beyond.
The cd command changes the current working directory. It is one of the most frequently used commands in any Linux session.
cd /home/user — navigate to absolute pathcd .. — go up one directory levelcd ~ — go to home directorycd - — return to previous directoryCreates a new directory. Use -p to create nested directories in one command.
mkdir mydir — create a directorymkdir -p a/b/c — create nested dirsRemoves an empty directory. For non-empty directories, use rm -r instead.
rmdir mydir — remove empty dirrmdir -p a/b/c — remove nested empty dirsPrint Working Directory — shows the full path of your current location.
pwd → /home/user/projects
List directory contents. Use ls -la for detailed listing including hidden files.
ls -la /etc
Display directory structure as a visual tree. Use -L 2 to limit depth.
tree -L 2 /var
Search for files in a directory hierarchy in real time.
find / -name "*.log" — find all .log filesfind . -type d — find all directoriesfind /tmp -mtime +7 — files older than 7 daysQuickly find files using a pre-built database. Run updatedb to refresh the index.
locate nginx.conf — find file by namelocate -i readme — case-insensitive searchCopy files or directories. Use -r for recursive copy of directories.
cp file.txt /backup/ | cp -r dir/ /backup/
Move files or rename them. Works across directories.
mv old.txt new.txt | mv file.txt /tmp/
Delete files or directories. Use -rf with caution — it is irreversible.
rm file.txt | rm -rf /tmp/olddir
Concatenate and display file contents. Also used to combine files.
cat file.txt — display filecat a.txt b.txt > c.txt — combine filesView the beginning or end of a file. Use -n to specify line count. tail -f follows live log output.
head -n 20 file.txttail -f /var/log/syslogView file contents one page at a time with forward and backward navigation. Preferred over more.
less /var/log/auth.logq to quit, / to searchG to jump to endSimilar to less but only allows forward navigation through a file.
more file.txtSpace to advance a pageq to quitCreate an empty file or update a file's timestamp.
touch newfile.txt
Create hard or symbolic links between files.
ln -s /etc/nginx nginx-link
Securely overwrite a file to make recovery difficult before deletion.
shred -u secret.txt
Print text or variable values to the terminal.
echo "Hello World" | echo $HOME
Convert tabs to spaces in a file or input stream.
expand -t 4 file.txt
Wrap long lines of text to a specified width.
fold -w 80 longfile.txt
Search for patterns in files using regular expressions. One of the most powerful Linux tools.
grep "error" /var/log/sysloggrep -r "TODO" ./src/ — recursive searchgrep -i "warning" file.log — case-insensitiveegrep supports extended regex (same as grep -E). fgrep treats the pattern as a fixed string, not regex.
egrep "error|warn" file.logfgrep "192.168.1.1" access.logA powerful pattern-scanning and processing language. Ideal for column-based data.
awk '{print $1}' file.txt — print first columnawk -F: '{print $1}' /etc/passwdawk '/error/ {print}' log.txtStream editor for filtering and transforming text. Commonly used for find-and-replace.
sed 's/old/new/g' file.txtsed -n '5,10p' file.txt — print lines 5–10sed '/^#/d' config.txt — delete comment linesSort lines of text files alphabetically or numerically.
sort file.txt | sort -n numbers.txt | sort -r file.txt
Extract specific columns or fields from each line of a file.
cut -d: -f1 /etc/passwd — extract usernames
Translate or delete characters from input.
echo "hello" | tr 'a-z' 'A-Z' → HELLO
Compare two files line by line and show differences. Use -u for unified format (used in patches).
diff file1.txt file2.txt | diff -u old.c new.c
Compare two files byte by byte. Returns the position of the first difference.
cmp file1.bin file2.bin
Split a large file into smaller pieces by line count or byte size.
split -l 1000 bigfile.txt part_
Print file contents in reverse line order (opposite of cat).
tac file.txt
Merge lines of files side by side, separated by a delimiter.
paste file1.txt file2.txt
Join lines of two files on a common field, like a database JOIN.
join file1.txt file2.txt
Count lines, words, and characters in a file.
wc -l file.txt — count lineswc -w file.txt — count wordswc -c file.txt — count bytesfmt reformats paragraph text to a specified width. column formats input into aligned columns for readable output.
fmt -w 72 essay.txtcolumn -t data.txtDisplay a snapshot of currently running processes. Use ps aux for a full listing of all processes.
ps aux — all processesps -ef | grep nginx — find specific processtop provides a real-time dynamic view of running processes. htop is an enhanced interactive version with color and mouse support.
top — live process monitorhtop — interactive process viewerSend a signal to a process, typically to terminate it. Use kill -9 to force-kill.
kill 1234 | kill -9 5678 | killall nginx
Resume a suspended job in the background so the terminal remains free.
bg %1 — resume job 1 in background
Bring a background job to the foreground of the current terminal.
fg %1 — bring job 1 to foreground
Trace system calls and signals made by a process. Invaluable for debugging.
strace ls — trace ls commandstrace -p 1234 — attach to running processpmap reports the memory map of a process. pidof finds the PID of a running program by name.
pmap 1234 — memory map of PID 1234pidof nginx — get nginx PIDMeasure the execution time of a command.
time ./myscript.sh — shows real, user, and sys time
Execute a command repeatedly at a set interval and display the output.
watch -n 2 df -h — refresh disk usage every 2s
Report CPU statistics per processor. Part of the sysstat package.
mpstat -P ALL 1 — per-CPU stats every second
Create a new user account. Use -m to create a home directory.
useradd -m -s /bin/bash alice
Delete a user account. Use -r to also remove the home directory.
userdel -r alice
Modify an existing user account — change shell, group, home directory, etc.
usermod -aG sudo alice
Change a user's password. Run as root to change any user's password.
passwd — change your own passwordpasswd alice — change alice's passwordchpasswd updates passwords in batch from a file. chage manages password expiry and aging policies.
chpasswd < users.txtchage -l alice — view expiry infochage -M 90 alice — set 90-day expiryShow who is currently logged into the system, including login time and terminal.
who | who -a — all details
Print the username of the currently logged-in user.
whoami → alice
Display user and group IDs for the current or specified user.
id | id alice — show UID, GID, groups
Display information about a user including login name, real name, terminal, and idle time.
finger alice — info about alicefinger — list all logged-in userschfn changes a user's full name and contact info. chsh changes the default login shell.
chfn alice — update finger infochsh -s /bin/zsh alice — set zsh as shellChange the read, write, and execute permissions of files and directories. Permissions can be set using symbolic or octal notation.
chmod 755 script.sh — rwxr-xr-xchmod +x script.sh — add executechmod -R 644 /var/www — recursivechmod u+w,g-r file.txt — symbolic modeChange the owner and/or group of a file or directory.
chown alice:staff file.txt | chown -R www-data /var/www
Change special file attributes on Linux filesystems (e.g., make a file immutable).
chattr +i file.txt — make immutable
Mount a filesystem or device to a directory in the file tree.
mount /dev/sdb1 /mnt/usb
Create or delete a user group on the system.
groupadd developers — create groupgroupdel developers — delete groupgroupmod modifies a group's name or GID. groups lists all groups a user belongs to.
groupmod -n devs developersgroups alice — show alice's groupsAdminister /etc/group and /etc/gshadow. Add or remove users from groups and set group passwords.
gpasswd -a alice developers — add alice to group
gpasswd -d alice developers — remove alice
Verify the integrity of group files. Checks for invalid entries in /etc/group and /etc/gshadow.
grpck — run group file integrity check
Send ICMP echo requests to test if a host is reachable and measure round-trip time.
ping google.comping -c 4 192.168.1.1 — send 4 packetsTrace the route packets take to reach a destination, showing each hop along the way.
traceroute google.comtracepath 8.8.8.8 — no root requiredDisplay or configure network interfaces. Older tool, largely replaced by ip on modern systems.
ifconfig — show all interfacesifconfig eth0 up — bring interface upModern replacement for ifconfig, route, and arp. Manages addresses, routes, and links.
ip addr show — show IP addressesip route show — show routing tableip link set eth0 upSecurely connect to a remote machine over an encrypted channel.
ssh alice@192.168.1.10
ssh -p 2222 alice@server.com
Securely copy files between hosts over SSH.
scp file.txt alice@server:/tmp/
scp -r /local/dir alice@server:/remote/
Efficiently sync files locally or over SSH, transferring only changed data.
rsync -avz /src/ alice@server:/dst/
Transfer data from or to a server using various protocols. Highly versatile for API testing and downloads.
curl https://example.comcurl -O https://example.com/file.zipcurl -X POST -d '{"key":"val"}' api.comNon-interactive downloader supporting HTTP, HTTPS, and FTP. Great for recursive downloads.
wget https://example.com/file.tar.gzwget -r https://example.com — recursivewget -c file.zip — resume downloadDisplay network connections, routing tables, and interface statistics.
netstat -tuln — show listening ports
Configure Linux kernel firewall rules for packet filtering and NAT.
iptables -L — list rules | iptables-save > rules.txt
Command-line tool for NetworkManager — manage connections, Wi-Fi, and VPNs.
nmcli con show | nmcli dev wifi connect SSID
Display or set the system's hostname. hostnamectl provides more control on systemd systems.
hostname | hostnamectl set-hostname myserver
Query DNS servers to resolve domain names to IP addresses and vice versa.
nslookup google.com | nslookup 8.8.8.8
Simple DNS lookup utility. Converts names to IPs and IPs to names.
host google.com | host 8.8.8.8
The "Swiss Army knife" of networking — read/write data across TCP/UDP connections. Used for port scanning, file transfer, and debugging.
nc -zv host 80 — test port 80nc -l 1234 > file.txt — receive filearp displays and modifies the ARP cache (IP-to-MAC mappings). vnstat monitors network traffic usage over time.
arp -a — show ARP tablevnstat -i eth0 — traffic statsModern, user-friendly package manager for Debian/Ubuntu. Combines the best of apt-get and apt-cache.
apt update && apt upgrade | apt install nginx
Classic package management tool. Preferred in scripts for its stable interface.
apt-get install vim | apt-get remove vim
Advanced package manager with a text-based UI and better dependency resolution.
aptitude install nginx | aptitude search vim
Schedule commands to run automatically at specified times. Edit your crontab with crontab -e. The cron syntax is: minute hour day month weekday command.
crontab -e — edit cron jobscrontab -l — list cron jobs0 2 * * * /backup.sh — run at 2am daily*/5 * * * * /check.sh — every 5 minutesSchedule a command to run once at a specific time in the future.
echo "reboot" | at 02:00
at now + 1 hour — then type commands
List pending jobs in the at queue.
atq — show all queued jobs
Remove a job from the at queue by its job number.
atrm 3 — remove job number 3
Report the amount of disk space used and available on filesystems.
df -h — human-readable sizesdf -T — show filesystem typedf /home — specific mount pointEstimate file and directory space usage.
du -sh /var/log — total size of dirdu -ah /home — all files with sizesdu -sh * | sort -h — sorted by sizePartition table manipulator for MBR disks. Use gdisk for GPT.
fdisk -l — list partitions | fdisk /dev/sdb
Curses-based interactive partition editor — easier to use than fdisk.
cfdisk /dev/sdb
Check and repair FAT filesystems (MS-DOS file system checker).
dosfsck -a /dev/sdb1 — auto-repair
dump creates backups of ext2/3/4 filesystems. restore recovers files from those backups.
dump -0uf /backup/root.dump /restore -rf /backup/root.dumpFlush filesystem buffers, writing all pending data to disk. Run before unmounting a device.
sync — flush all buffers to diskumount on removable mediatar creates and extracts archive files. Combine with compression tools like gzip or bzip2 for compressed archives.
tar -czf archive.tar.gz /dir — create gzip archivetar -xzf archive.tar.gz — extract gzip archivetar -cjf archive.tar.bz2 /dir — bzip2 archivetar -tf archive.tar.gz — list contentsCompress or decompress files using the GNU zip algorithm.
gzip file.txt → file.txt.gz
gunzip file.txt.gz
Higher compression ratio than gzip, but slower. Produces .bz2 files.
bzip2 file.txt → file.txt.bz2
Create and extract ZIP archives, compatible with Windows.
zip archive.zip file1 file2
unzip archive.zip
Print system information including kernel name, version, and architecture.
uname -a — all info | uname -r — kernel version
List block devices (disks, partitions, and their mount points) in a tree format.
lsblk | lsblk -f — show filesystems
lsusb lists USB devices. lshw provides detailed hardware configuration.
lsusb | lshw -short
Display the amount of free and used memory in the system, including swap.
free -h — human-readable outputfree -m — output in megabytesiostat reports CPU and I/O statistics for devices. hdparm gets or sets hard disk parameters.
iostat -x 1 — extended stats every 1shdparm -I /dev/sda — disk infohdparm -tT /dev/sda — benchmark diskPrint or control the kernel ring buffer — useful for diagnosing hardware and boot issues.
dmesg | tail -20 | dmesg | grep error
Dump DMI/SMBIOS data — shows hardware info like CPU, RAM, BIOS, and motherboard details.
dmidecode -t memory | dmidecode -t bios
Show battery status, AC adapter state, and thermal information on laptops.
acpi -b — battery | acpi -t — temperature
systemctl is the primary tool for managing systemd services and the system state. Start, stop, enable, and inspect services.
systemctl start nginx — start servicesystemctl stop nginx — stop servicesystemctl enable nginx — start on bootsystemctl status nginx — check statussystemctl list-units — list all unitsHalt the system immediately, stopping all processes without powering off.
halt | halt -f — force halt
Restart the system gracefully, shutting down all services first.
reboot | reboot -f — force reboot
poweroff halts and powers off the machine. shutdown schedules a shutdown with an optional message.
shutdown -h now | shutdown -r +5 "Rebooting"
Query and display logs from the systemd journal. The primary logging tool on modern Linux systems.
journalctl -xe — recent errorsjournalctl -u nginx — service logsjournalctl --since "1 hour ago"Collect, report, and save system activity information (CPU, memory, I/O). Part of the sysstat package.
sar -u 1 5 — CPU usage, 5 samplessar -r — memory statssar -b — I/O statsReport virtual memory, processes, I/O, and CPU activity statistics.
vmstat 1 5 — 5 reports, 1 second apart
Show how long the system has been running, plus load averages for 1, 5, and 15 minutes.
uptime → up 3 days, load average: 0.5, 0.3, 0.2
Versatile resource statistics tool combining vmstat, iostat, and netstat output.
dstat -cdngy — CPU, disk, net, page, sys
Record everything printed to the terminal into a file. Useful for auditing and documentation.
script session.log — start recordingexit — stop recordingscriptreplay timing.log session.logShow a listing of last logged-in users, reading from /var/log/wtmp.
last — all recent loginslast alice — logins for alicelast reboot — system rebootsCompute or verify MD5 checksums to confirm file integrity after download or transfer.
md5sum file.iso | md5sum -c checksums.md5
Calculate a CRC checksum and byte count for a file.
cksum file.txt — outputs checksum and size
Compute a simple checksum and block count for a file.
sum file.txt — legacy checksum tool
Display or set the system date and time. Supports custom format strings.
date | date "+%Y-%m-%d %H:%M" | date -s "2024-01-01 12:00"
Display a calendar for the current or specified month and year.
cal | cal 12 2024 — December 2024
Read or set the hardware (BIOS) clock. Sync it with the system clock.
hwclock --show | hwclock --systohc
Create shortcuts for long or frequently used commands. Add to ~/.bashrc for persistence.
alias ll='ls -la'alias gs='git status'unalias ll — remove aliasSet environment variables and make them available to child processes.
export PATH=$PATH:/usr/local/binexport EDITOR=vimexport -p — list all exported varsConditional execution based on exit status or test expressions.
if [ -f file.txt ]; then echo "exists"; fi
Iterate over a list of items or a range of numbers.
for i in 1 2 3; do echo $i; done
Execute commands repeatedly while or until a condition is true.
while true; do sleep 1; done
Read a line of input from the user or a file into a variable.
read -p "Enter name: " name
echo $name
Format and print data, similar to C's printf. More powerful than echo.
printf "Hello, %s!\n" "$name"
Evaluate and execute a string as a shell command. Use with caution.
cmd="ls -la"; eval $cmd
Declare variables and give them attributes (integer, array, read-only, etc.).
declare -i num=5 — integer variabledeclare -r PI=3.14 — read-onlydeclare -a arr=(1 2 3) — arraysource (or .) executes a script in the current shell, loading its variables. type shows how a command name is interpreted.
source ~/.bashrctype ls — is it alias, function, or binary?Evaluate arithmetic and string expressions in shell scripts.
expr 5 + 3 → 8
expr length "hello" → 5
Print the prime factorization of a given number.
factor 60 → 60: 2 2 3 5
Generate a sequence of numbers with optional step and format.
seq 1 10 | seq 0 2 10 — even numbers
Automate interactive command-line programs by scripting expected prompts and responses. Useful for automating SSH logins and FTP sessions.
expect script.exp — run expect scriptspawn, expect, send commandsRun a program in a new session, detached from the controlling terminal. Useful for daemonizing processes.
setsid ./myscript.shList currently loaded kernel modules and their dependencies.
lsmod | lsmod | grep bluetooth
Insert a module into the Linux kernel. Requires the full path to the .ko file.
insmod /lib/modules/mymod.ko
Remove a loaded module from the kernel. Use modprobe -r for safer removal with dependency handling.
rmmod mymod
Generate a list of module dependencies and map files. Run after installing a new kernel module.
depmod -a — update all module dependenciesmodprobe can find new modulesDisplay information about a kernel module — author, description, parameters, and license.
modinfo bluetoothmodinfo -F description e1000GNU C Compiler — compile C source files into executables.
gcc -o myapp main.c | gcc -Wall -g main.c
GNU C++ Compiler — compile C++ source files.
g++ -o myapp main.cpp | g++ -std=c++17 main.cpp
GNU Debugger — step through code, set breakpoints, and inspect variables at runtime.
gdb ./myapp | gdb -p 1234 — attach to process
Generate portable configure scripts and Makefile.in templates for building software across different platforms.
autoconf — generate configure scriptautomake --add-missingautoreconf -i — run all auto toolsctags generates tag files for source code navigation in editors. readelf displays information about ELF binary files.
ctags -R . — tag all source filesreadelf -h myapp — ELF header infoThe C preprocessor — expands macros, includes, and conditional compilation directives before compilation.
cpp main.c | cpp -DDEBUG main.c
Convert program addresses into file names and line numbers for debugging crash reports.
addr2line -e myapp 0x4005f0
Generate an index for a static library archive, making linking faster.
ranlib libmylib.a
Display the manual page for a command. The most important help tool in Linux.
man ls — manual for lsman 5 passwd — section 5 of passwdman -k keyword — search manualsinfo provides more detailed GNU documentation. apropos searches man page descriptions. whatis gives a one-line description.
info bashapropos networkwhatis ls | which python3Create multiple terminal sessions within one window. Sessions persist after disconnection — ideal for remote work.
screen — start new sessionscreen -r — reattach to sessionCtrl+A D — detach from sessionstty configures terminal settings. tty prints the terminal device name. reset reinitializes a garbled terminal.
stty -a — show all settingstty → /dev/pts/0reset — fix broken terminalOpen a terminal line and invite a login. Used by init/systemd to manage virtual console logins.
agetty tty1 38400 — open login on tty1
Change the active virtual terminal (console). Equivalent to pressing Ctrl+Alt+F1.
chvt 2 — switch to virtual terminal 2
Display the keycodes or scancodes of keys pressed on the keyboard. Useful for keyboard mapping.
showkey — show keycodes | showkey -s — scancodes
The CUPS print server daemon. Manages print queues and printer drivers on Linux.
systemctl start cups | Access at http://localhost:631
Play audio files from the command line using ALSA.
aplay sound.wav | aplay -l — list sound cards
Control ALSA sound card mixer settings from the command line.
amixer set Master 80% | amixer get Master
mail sends and reads email from the command line. mailq displays the mail transfer agent's queue of pending messages.
echo "Hello" | mail -s "Subject" user@hostmailq — show pending mail queuewrite sends a message to a specific logged-in user. wall broadcasts a message to all logged-in users.
write alice pts/1 — message to alicewall "System going down in 5 min"biff y — notify on new mailRedirect stdout to a file, overwriting existing content.
ls > files.txt — save listing to file
Redirect stdout to a file, appending to existing content.
echo "log entry" >> app.log
Redirect stderr (2>) or both stdout and stderr (&>) to a file.
cmd 2> err.log | cmd &> all.log
Send the output of one command as input to another. The backbone of Linux command chaining.
ps aux | grep nginxcat file.txt | sort | uniqls -la | less< redirects a file as stdin to a command. << (here-doc) provides inline multi-line input.
sort < unsorted.txtcat << EOF — start here-docmysql db < script.sqlVim is a powerful terminal text editor. Understanding its modal nature is key — press i to enter Insert mode, Esc to return to Normal mode, and :wq to save and quit.
gg — go to beginning of fileG — go to end of file0 — go to beginning of line$ — go to end of lineCtrl+F — scroll forward one page/pattern — search forward?pattern — search backwardn — next match | N — previous match* — search word under cursor:s/old/new/ — replace first on line:s/old/new/g — replace all on line:%s/old/new/g — replace all in file:g/pattern/d — delete matching linesdd — delete current lineD — delete to end of linedw — delete word forwarddb — delete word backwardyy — copy (yank) current linep — paste after cursoru — undo | Ctrl+R — redo:w — save file:q! — quit without saving:wq — save and quit:e file.txt — open another file:split file.txt — horizontal splitCtrl+W W — switch between splits:bn / :bp — next/prev buffer
Linux Commands Cheat Sheet