🐧 Linux Command Cheat Sheet

Complete reference for essential Linux commands with examples, syntax, and practical usage tips

📚 Practice what you've learned with our Linux Flashcards

Showing 106 commands
ls
File Operations

List directory contents

Syntax:

ls [options] [directory]

Examples:

ls

List files in current directory

ls -la

List all files including hidden with detailed info

ls -lh

List with human-readable file sizes

ls *.txt

List only .txt files

Notes:

Common options: -l (long format), -a (all files), -h (human readable), -R (recursive)

cp
File Operations

Copy files and directories

Syntax:

cp [options] source destination

Examples:

cp file.txt backup.txt

Copy file to new name

cp -r folder/ backup/

Copy directory recursively

cp *.txt /backup/

Copy all .txt files to backup directory

cp -p file.txt /dest/

Copy preserving attributes

Notes:

Use -r for directories, -p to preserve permissions and timestamps

mv
File Operations

Move/rename files and directories

Syntax:

mv [options] source destination

Examples:

mv oldname.txt newname.txt

Rename a file

mv file.txt /new/location/

Move file to different directory

mv *.txt documents/

Move all .txt files to documents folder

mv folder1/ folder2/

Rename/move directory

Notes:

Works for both moving and renaming files and directories

rm
File Operations

Remove files and directories

Syntax:

rm [options] file/directory

Examples:

rm file.txt

Delete a file

rm -r folder/

Delete directory and contents recursively

rm -f file.txt

Force delete without confirmation

rm *.tmp

Delete all .tmp files

Notes:

Be careful! -f forces deletion, -r removes directories recursively

touch
File Operations

Create empty files or update timestamps

Syntax:

touch [options] filename

Examples:

touch newfile.txt

Create empty file

touch file1.txt file2.txt

Create multiple files

touch -t 202312250800 file.txt

Set specific timestamp

Notes:

Creates file if it doesn't exist, updates timestamp if it does

ln
File Operations

Create links between files

Syntax:

ln [options] target linkname

Examples:

ln file.txt hardlink.txt

Create hard link

ln -s /path/to/file symlink

Create symbolic link

ln -sf /new/target existing_link

Force create/update symbolic link

Notes:

Use -s for symbolic links, hard links share same inode

pwd
Directory Operations

Print working directory

Syntax:

pwd

Examples:

pwd

Show current directory path

Notes:

Displays the full path of current directory

cd
Directory Operations

Change directory

Syntax:

cd [directory]

Examples:

cd /home/user

Change to specific directory

cd ..

Go up one directory level

cd ~

Go to home directory

cd -

Go to previous directory

Notes:

~ represents home directory, .. means parent directory

mkdir
Directory Operations

Create directories

Syntax:

mkdir [options] directory

Examples:

mkdir newdir

Create single directory

mkdir -p path/to/deep/dir

Create nested directories

mkdir dir1 dir2 dir3

Create multiple directories

mkdir -m 755 mydir

Create with specific permissions

Notes:

Use -p to create parent directories if they don't exist

rmdir
Directory Operations

Remove empty directories

Syntax:

rmdir [options] directory

Examples:

rmdir emptydir

Remove empty directory

rmdir -p path/to/empty/dirs

Remove empty directory hierarchy

Notes:

Only works on empty directories, use 'rm -r' for non-empty directories

cat
Text Processing

Display file contents

Syntax:

cat [options] file

Examples:

cat file.txt

Display file contents

cat file1.txt file2.txt

Display multiple files

cat -n file.txt

Display with line numbers

cat > newfile.txt

Create file from input

Notes:

Can concatenate multiple files, use > to redirect output

less
Text Processing

View file contents page by page

Syntax:

less [options] file

Examples:

less file.txt

View file with pagination

less +50 file.txt

Start at line 50

command | less

Pipe command output to less

Notes:

Use space/f for next page, b for previous, q to quit, / to search

head
Text Processing

Display first lines of file

Syntax:

head [options] file

Examples:

head file.txt

Show first 10 lines

head -n 20 file.txt

Show first 20 lines

head -c 100 file.txt

Show first 100 characters

Notes:

Default shows first 10 lines, use -n to specify number of lines

tail
Text Processing

Display last lines of file

Syntax:

tail [options] file

Examples:

tail file.txt

Show last 10 lines

tail -n 20 file.txt

Show last 20 lines

tail -f logfile.txt

Follow file changes in real-time

tail -F logfile.txt

Follow file even if recreated

Notes:

Use -f to monitor log files, -F handles file rotation

grep
Text Processing

Search text patterns in files

Syntax:

grep [options] pattern file

Examples:

grep 'error' logfile.txt

Search for 'error' in file

grep -i 'ERROR' file.txt

Case insensitive search

grep -r 'pattern' directory/

Recursive search in directory

grep -v 'exclude' file.txt

Show lines NOT containing pattern

Notes:

Use -i for case insensitive, -r for recursive, -v to invert match

sed
Text Processing

Stream editor for filtering and transforming text

Syntax:

sed [options] 'command' file

Examples:

sed 's/old/new/g' file.txt

Replace all occurrences of 'old' with 'new'

sed -i 's/old/new/g' file.txt

Replace in-place (modify original file)

sed -n '10,20p' file.txt

Print lines 10 to 20

sed '/pattern/d' file.txt

Delete lines containing pattern

Notes:

Powerful stream editor, use -i to modify files in place

awk
Text Processing

Pattern scanning and processing language

Syntax:

awk 'pattern {action}' file

Examples:

awk '{print $1}' file.txt

Print first column

awk -F: '{print $1}' /etc/passwd

Use colon as field separator

awk 'length > 80' file.txt

Print lines longer than 80 characters

awk '{sum+=$1} END {print sum}' file.txt

Sum first column values

Notes:

Powerful text processing tool, $1, $2, etc. refer to columns

sort
Text Processing

Sort lines in text files

Syntax:

sort [options] file

Examples:

sort file.txt

Sort lines alphabetically

sort -n numbers.txt

Sort numerically

sort -r file.txt

Sort in reverse order

sort -k2 file.txt

Sort by second column

Notes:

Use -n for numeric sort, -r for reverse, -k to specify sort column

uniq
Text Processing

Remove duplicate adjacent lines

Syntax:

uniq [options] file

Examples:

uniq file.txt

Remove duplicate adjacent lines

sort file.txt | uniq

Sort then remove all duplicates

uniq -c file.txt

Count occurrences of each line

uniq -d file.txt

Show only duplicate lines

Notes:

Only removes adjacent duplicates, often used with sort

wc
Text Processing

Count lines, words, and characters

Syntax:

wc [options] file

Examples:

wc file.txt

Count lines, words, and characters

wc -l file.txt

Count only lines

wc -w file.txt

Count only words

wc -c file.txt

Count only characters

Notes:

Default shows lines, words, and characters count

diff
Text Processing

Compare files line by line

Syntax:

diff [options] file1 file2

Examples:

diff file1.txt file2.txt

Compare two files

diff -u file1.txt file2.txt

Compare with unified format

diff -r dir1 dir2

Compare two directories recursively

Notes:

Shows the differences between two files. Useful for tracking changes.

nano
Text Processing

Simple text editor for terminal

Syntax:

nano [options] [file]

Examples:

nano file.txt

Open or create file in nano

nano +10 file.txt

Open file at line 10

nano -w file.txt

Disable line wrapping

Notes:

User-friendly editor with on-screen help. Ctrl+O to save, Ctrl+X to exit, Ctrl+K to cut, Ctrl+U to paste

vi
Text Processing

Powerful text editor (Vi/Vim)

Syntax:

vi [options] [file]

Examples:

vi file.txt

Open or create file in vi

vi +10 file.txt

Open file at line 10

vi +/pattern file.txt

Open file and jump to pattern

Notes:

Modal editor: i for insert mode, ESC for normal mode, :w to save, :q to quit, :wq to save and quit, :q! to quit without saving

clear
System Administration

Clear the terminal screen

Syntax:

clear

Examples:

clear

Clears all previous commands and output from the terminal screen.

Notes:

Same as pressing Ctrl+L in most terminals.

man
System Administration

Display the manual page for a command

Syntax:

man [command]

Examples:

man ls

Show the manual page for the 'ls' command.

Notes:

Provides detailed information about commands.

ps
System Information

Display running processes

Syntax:

ps [options]

Examples:

ps

Show processes for current terminal

ps aux

Show all processes with detailed info

ps -ef

Show all processes in full format

ps -u username

Show processes for specific user

Notes:

Common options: aux (all processes), -ef (full format), -u (by user)

top
System Information

Display running processes dynamically

Syntax:

top [options]

Examples:

top

Show real-time process information

top -u username

Show processes for specific user

top -p PID

Monitor specific process

Notes:

Interactive tool: q to quit, k to kill process, r to renice

htop
System Information

Interactive process viewer (enhanced top)

Syntax:

htop [options]

Examples:

htop

Launch interactive process viewer

htop -u username

Show processes for specific user

Notes:

More user-friendly than top, requires installation on many systems

df
System Information

Display disk space usage

Syntax:

df [options] [filesystem]

Examples:

df

Show disk usage for all filesystems

df -h

Show in human-readable format

df -T

Show filesystem types

df /home

Show usage for specific mount point

Notes:

Use -h for human-readable sizes (GB, MB, etc.)

du
System Information

Display directory space usage

Syntax:

du [options] [directory]

Examples:

du -h

Show directory sizes in human-readable format

du -sh *

Show size of each item in current directory

du -sh /var/log

Show total size of specific directory

du -h --max-depth=1

Show sizes one level deep

Notes:

Use -h for human-readable, -s for summary, --max-depth to limit recursion

free
System Information

Display memory usage

Syntax:

free [options]

Examples:

free

Show memory usage in KB

free -h

Show in human-readable format

free -m

Show in MB

free -s 5

Update every 5 seconds

Notes:

Shows total, used, free, shared, buffer/cache, and available memory

uname
System Information

Display system information

Syntax:

uname [options]

Examples:

uname

Show kernel name

uname -a

Show all system information

uname -r

Show kernel release

uname -m

Show machine architecture

Notes:

Common options: -a (all), -r (kernel release), -m (machine type)

whoami
System Information

Display current username

Syntax:

whoami

Examples:

whoami

Show current user

Notes:

Simple command to check which user you're logged in as

id
System Information

Display user and group IDs

Syntax:

id [username]

Examples:

id

Show current user's UID, GID, and groups

id username

Show specific user's ID information

id -u

Show only user ID

id -g

Show only group ID

Notes:

Shows UID (user ID), GID (group ID), and all group memberships

uptime
System Information

Show how long system has been running

Syntax:

uptime

Examples:

uptime

Show how long system has been running

Notes:

Provides a quick overview of system status

lscpu
System Information

Display information about the CPU architecture

Syntax:

lscpu

Examples:

lscpu

Show CPU details like architecture, cores, and speed.

Notes:

Provides a summary of CPU characteristics.

lshw
System Information

List hardware configuration

Syntax:

lshw [options]

Examples:

lshw

List all hardware components.

lshw -short

List hardware in a summary format.

lshw -class network

List only network hardware.

Notes:

Requires root privileges for full details. Use 'sudo lshw'.

vmstat
System Information

Report virtual memory statistics

Syntax:

vmstat [options] [delay] [count]

Examples:

vmstat

Display system statistics summary

vmstat 2 5

Display statistics every 2 seconds, 5 times

vmstat -s

Display detailed memory statistics

vmstat -d

Display disk statistics

Notes:

Shows memory, swap, I/O, system, and CPU activity. Format: delay (seconds) count (iterations)

iostat
System Information

Report CPU and I/O statistics

Syntax:

iostat [options] [delay] [count]

Examples:

iostat

Display CPU and disk I/O statistics

iostat 2 5

Display statistics every 2 seconds, 5 times

iostat -x

Display extended statistics

iostat -d

Display only disk statistics

Notes:

Part of sysstat package. Shows CPU utilization and device I/O statistics. Use -x for extended info

shutdown
System Administration

Shutdown or reboot the system

Syntax:

shutdown [options] [time] [message]

Examples:

shutdown now

Shutdown the system immediately.

shutdown -r now

Reboot the system immediately.

shutdown +10

Shutdown in 10 minutes.

Notes:

Can be used to schedule shutdowns. `reboot` is often a shortcut for `shutdown -r now`.

reboot
System Administration

Reboot the system

Syntax:

reboot

Examples:

reboot

Reboot the system immediately.

Notes:

Often equivalent to 'shutdown -r now'.

fdisk
System Administration

Partition table manipulator for Linux

Syntax:

fdisk [options] device

Examples:

sudo fdisk -l

List all partitions on all disks

sudo fdisk /dev/sda

Start fdisk on /dev/sda for partitioning

sudo fdisk -l /dev/sda

List partitions on specific disk

Notes:

Interactive tool for disk partitioning. Use with caution as it can destroy data. Press 'm' for help when in interactive mode

blkid
System Administration

Locate and print block device attributes

Syntax:

blkid [options] [device]

Examples:

blkid

Show UUID and filesystem type for all devices

blkid /dev/sda1

Show attributes for specific partition

blkid -o list

Show detailed device information in list format

Notes:

Useful for finding UUIDs needed for /etc/fstab. Shows filesystem type, UUID, and labels

lsblk
System Administration

List information about block devices

Syntax:

lsblk [options] [device]

Examples:

lsblk

List all block devices in tree format

lsblk -f

Show filesystem information

lsblk -a

List all devices including empty ones

lsblk -o NAME,SIZE,TYPE,MOUNTPOINT

Custom column output

Notes:

Shows device names, sizes, mount points, and relationships between devices in an easy-to-read tree format

make
System Administration

Build automation tool

Syntax:

make [options] [target]

Examples:

make

Build default target from Makefile

make install

Run install target

make clean

Clean up build artifacts

make -j4

Build with 4 parallel jobs

Notes:

Reads Makefile to determine how to build a program. Use -j for parallel builds, -n for dry run

journalctl
System Administration

Query and display systemd journal logs

Syntax:

journalctl [options]

Examples:

journalctl

View all journal entries

journalctl -f

Follow journal in real-time

journalctl -u nginx

Show logs for specific service

journalctl --since '1 hour ago'

Show logs from last hour

journalctl -p err

Show only error messages

Notes:

Systemd logging system. Use -f to follow, -u for specific service, -p for priority (emerg, alert, crit, err, warning)

dmesg
System Administration

Display kernel ring buffer messages

Syntax:

dmesg [options]

Examples:

dmesg

Display all kernel messages

dmesg -w

Follow kernel messages in real-time

dmesg -T

Show human-readable timestamps

dmesg | grep -i error

Search for error messages

dmesg -l err,warn

Show only errors and warnings

Notes:

Shows kernel messages, useful for hardware issues and boot problems. Use -T for timestamps, -w to follow

kill
Process Management

Terminate processes by PID

Syntax:

kill [signal] PID

Examples:

kill 1234

Send TERM signal to process 1234

kill -9 1234

Force kill process 1234

kill -HUP 1234

Send hangup signal to reload config

kill -l

List all available signals

Notes:

Common signals: -9 (KILL), -15 (TERM), -1 (HUP), -2 (INT)

killall
Process Management

Terminate processes by name

Syntax:

killall [options] processname

Examples:

killall firefox

Kill all firefox processes

killall -9 python

Force kill all python processes

killall -u username

Kill all processes owned by user

Notes:

Kills processes by name instead of PID, be careful with common names

jobs
Process Management

Display active jobs

Syntax:

jobs [options]

Examples:

jobs

List active jobs

jobs -l

List jobs with PID

jobs -r

List only running jobs

Notes:

Shows background jobs started from current shell

bg
Process Management

Put jobs in background

Syntax:

bg [job]

Examples:

bg

Put most recent job in background

bg %1

Put job 1 in background

Notes:

Use after Ctrl+Z to suspend, then bg to continue in background

fg
Process Management

Bring jobs to foreground

Syntax:

fg [job]

Examples:

fg

Bring most recent job to foreground

fg %1

Bring job 1 to foreground

Notes:

Brings background or suspended jobs back to foreground

nohup
Process Management

Run commands immune to hangups

Syntax:

nohup command [args] &

Examples:

nohup python script.py &

Run script in background, immune to logout

nohup ./long-running-task > output.log 2>&1 &

Run with output redirection

Notes:

Prevents process from being killed when terminal closes

nice
Process Management

Run command with modified scheduling priority

Syntax:

nice [options] command

Examples:

nice -n 10 command

Run command with lower priority

nice -n -10 command

Run command with higher priority (requires root)

nice command

Run with default niceness (10)

Notes:

Range is -20 (highest priority) to 19 (lowest). Default is 10. Negative values require root

renice
Process Management

Change priority of running processes

Syntax:

renice [priority] [options] [target]

Examples:

renice 10 -p 1234

Set process 1234 to priority 10

renice -5 -u username

Set all processes of user to priority -5

renice 15 -g groupname

Set all processes in group to priority 15

Notes:

Change priority of running processes. Use -p for PID, -u for user, -g for process group

ping
Network

Send ICMP echo requests to network hosts

Syntax:

ping [options] hostname/IP

Examples:

ping google.com

Ping Google continuously

ping -c 4 8.8.8.8

Ping 4 times then stop

ping -i 2 hostname

Ping every 2 seconds

ping -c 5 google.com

Ping 5 times

Notes:

Use Ctrl+C to stop, -c to limit count, -i to set interval

wget
Network

Download files from web

Syntax:

wget [options] URL

Examples:

wget https://example.com/file.zip

Download file

wget -O output.zip https://example.com/file.zip

Download with custom name

wget -r https://example.com/

Download website recursively

wget -c https://example.com/largefile.zip

Resume interrupted download

Notes:

Use -O for output filename, -c to resume downloads, -r for recursive

curl
Network

Transfer data from/to servers

Syntax:

curl [options] URL

Examples:

curl https://api.example.com

GET request to API

curl -O https://example.com/file.zip

Download file

curl -X POST -d 'data' https://api.example.com

POST request with data

curl -H 'Content-Type: application/json' -d '{"key":"value"}' https://api.example.com

POST JSON data

Notes:

More versatile than wget, supports many protocols and HTTP methods

ssh
Network

Secure Shell remote login

Syntax:

ssh [user@]hostname [command]

Examples:

ssh user@server.com

Connect to remote server

ssh -p 2222 user@server.com

Connect using specific port

ssh user@server.com 'ls -la'

Execute command on remote server

ssh -L 8080:localhost:80 user@server.com

Create local port forwarding

Notes:

Use -p for custom port, -L for port forwarding, -X for X11 forwarding

scp
Network

Secure copy files over SSH

Syntax:

scp [options] source destination

Examples:

scp file.txt user@server:/path/

Copy file to remote server

scp user@server:/path/file.txt .

Copy file from remote server

scp -r folder/ user@server:/path/

Copy directory recursively

scp -P 2222 file.txt user@server:/path/

Use specific port

Notes:

Like cp but over SSH, use -r for directories, -P for port

ifconfig
Networking

Display or configure network interfaces

Syntax:

ifconfig [interface]

Examples:

ifconfig

Display all network interfaces and their IP addresses.

ifconfig eth0

Display information for interface 'eth0'.

Notes:

Older command, often replaced by 'ip'. May require 'net-tools' package.

netstat
Networking

Display network connections, routing tables, etc.

Syntax:

netstat [options]

Examples:

netstat -tuln

List all listening TCP and UDP ports.

netstat -r

Display the kernel routing table.

Notes:

Older command, often replaced by 'ss'. May require 'net-tools' package.

ftp
Networking

File Transfer Protocol client

Syntax:

ftp [hostname]

Examples:

ftp ftp.example.com

Connect to an FTP server.

Notes:

Transfers data in plain text. Use SFTP for secure connections.

sftp
Networking

Secure File Transfer Protocol client

Syntax:

sftp [user@]hostname

Examples:

sftp user@example.com

Connect to an SFTP server securely.

Notes:

Uses SSH for a secure connection. Preferred over FTP.

traceroute
Networking

Trace the path packets take to a network host

Syntax:

traceroute [hostname]

Examples:

traceroute google.com

Trace the route to google.com.

Notes:

Useful for diagnosing network latency and routing issues.

ss
Networking

Socket statistics - investigate sockets

Syntax:

ss [options]

Examples:

ss -tuln

List all TCP/UDP listening sockets with port numbers

ss -tan

Show all TCP connections

ss -s

Show socket statistics summary

ss -tp

Show TCP connections with process info

Notes:

Modern replacement for netstat. Faster and more detailed. Use -t for TCP, -u for UDP, -l for listening, -n for numeric

ip
Networking

Show and manipulate routing, devices, policy routing

Syntax:

ip [options] object command

Examples:

ip addr show

Show all IP addresses

ip link show

Show all network interfaces

ip route show

Show routing table

ip addr add 192.168.1.100/24 dev eth0

Add IP address to interface

Notes:

Modern replacement for ifconfig. Objects: addr, link, route, neigh. Use 'ip -c' for colored output

nslookup
Networking

Query DNS servers for domain name or IP address

Syntax:

nslookup [options] [hostname] [server]

Examples:

nslookup google.com

Look up IP address for domain

nslookup 8.8.8.8

Reverse DNS lookup

nslookup google.com 8.8.8.8

Query specific DNS server

nslookup -type=mx google.com

Query MX records

Notes:

Interactive mode available by running without arguments. Use -type to query specific record types (A, MX, NS, etc.)

chmod
File Permissions

Change file permissions

Syntax:

chmod [options] mode file

Examples:

chmod 755 script.sh

Set rwxr-xr-x permissions

chmod +x script.sh

Add execute permission

chmod u+w,g-r file.txt

Add write for user, remove read for group

chmod -R 644 directory/

Set permissions recursively

Notes:

Numeric: 4=read, 2=write, 1=execute. Symbolic: u=user, g=group, o=other, a=all

chown
File Permissions

Change file ownership

Syntax:

chown [options] owner[:group] file

Examples:

chown user file.txt

Change owner to user

chown user:group file.txt

Change owner and group

chown :group file.txt

Change only group

chown -R user:group directory/

Change ownership recursively

Notes:

Use -R for recursive, format is owner:group

chgrp
File Permissions

Change group ownership

Syntax:

chgrp [options] group file

Examples:

chgrp staff file.txt

Change group to staff

chgrp -R developers project/

Change group recursively

Notes:

Changes only group ownership, use -R for recursive

umask
File Permissions

Set default file permissions

Syntax:

umask [mode]

Examples:

umask

Show current umask

umask 022

Set umask to 022 (755 for dirs, 644 for files)

umask 077

Set restrictive umask (700 for dirs, 600 for files)

Notes:

Umask subtracts from default permissions (777 for dirs, 666 for files)

tar
Archive/Compression

Archive files and directories

Syntax:

tar [options] archive files

Examples:

tar -czf archive.tar.gz folder/

Create compressed archive

tar -xzf archive.tar.gz

Extract compressed archive

tar -tzf archive.tar.gz

List contents of archive

tar -xzf archive.tar.gz -C /destination/

Extract to specific directory

Notes:

Common options: c=create, x=extract, z=gzip, f=file, t=list, v=verbose

gzip
Archive/Compression

Compress files

Syntax:

gzip [options] file

Examples:

gzip file.txt

Compress file (creates file.txt.gz)

gzip -d file.txt.gz

Decompress file

gzip -k file.txt

Compress but keep original

gzip -9 file.txt

Maximum compression

Notes:

Use -d to decompress, -k to keep original, -9 for best compression

unzip
Archive/Compression

Extract ZIP archives

Syntax:

unzip [options] archive.zip

Examples:

unzip archive.zip

Extract all files

unzip archive.zip -d /destination/

Extract to specific directory

unzip -l archive.zip

List contents without extracting

unzip archive.zip file.txt

Extract specific file

Notes:

Use -d for destination, -l to list, can extract specific files

zip
Archive/Compression

Create ZIP archives

Syntax:

zip [options] archive.zip files

Examples:

zip archive.zip file1.txt file2.txt

Create archive with files

zip -r archive.zip folder/

Create archive with directory

zip -u archive.zip newfile.txt

Update archive with new file

zip -9 archive.zip file.txt

Maximum compression

Notes:

Use -r for recursive (directories), -u to update, -9 for best compression

find
Search/Find

Search for files and directories

Syntax:

find [path] [expression]

Examples:

find . -name '*.txt'

Find all .txt files in current directory

find /home -user john

Find files owned by user john

find . -type f -size +100M

Find files larger than 100MB

find . -name '*.log' -mtime -7

Find .log files modified in last 7 days

Notes:

Very powerful, use -name for filename, -type for file type, -size for size, -mtime for modification time

locate
Search/Find

Find files by name (using database)

Syntax:

locate [options] pattern

Examples:

locate filename.txt

Find files named filename.txt

locate -i pattern

Case insensitive search

locate '*.conf'

Find all .conf files

Notes:

Fast but requires updatedb to be run regularly, searches indexed database

which
Search/Find

Locate command executable

Syntax:

which command

Examples:

which python

Find path to python executable

which -a python

Show all python executables in PATH

Notes:

Shows full path of executable commands, useful for finding binary locations

whereis
Search/Find

Locate binary, source, manual pages

Syntax:

whereis [options] command

Examples:

whereis python

Find python binary, source, and manual

whereis -b python

Find only binary

whereis -m python

Find only manual pages

Notes:

More comprehensive than which, finds binaries, sources, and manuals

sudo
System Control

Execute commands as another user

Syntax:

sudo [options] command

Examples:

sudo apt update

Run command as root

sudo -u username command

Run command as specific user

sudo -i

Start interactive root shell

sudo !!

Run previous command with sudo

Notes:

Requires user to be in sudoers file, use -i for interactive shell

su
System Control

Switch user

Syntax:

su [options] [username]

Examples:

su

Switch to root user

su username

Switch to specific user

su -

Switch to root with full environment

su - username

Switch user with full environment

Notes:

Use - to get full environment, exit to return to original user

systemctl
System Control

Control systemd services

Syntax:

systemctl [command] [service]

Examples:

systemctl status nginx

Check service status

systemctl start nginx

Start service

systemctl stop nginx

Stop service

systemctl enable nginx

Enable service at boot

systemctl list-units

List all active units

Notes:

Modern way to manage services on systemd systems

service
System Control

Control system services (legacy)

Syntax:

service [service] [command]

Examples:

service nginx status

Check service status

service nginx start

Start service

service nginx restart

Restart service

service --status-all

List all services and their status

Notes:

Older service management, use systemctl on modern systems

iptables
System Control

IPv4/IPv6 firewall administration tool

Syntax:

iptables [options] chain rule-specification

Examples:

sudo iptables -L

List all rules

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Allow incoming HTTP traffic

sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP

Block traffic from subnet

sudo iptables -F

Flush all rules

Notes:

Low-level firewall tool. Use -A to append, -D to delete, -L to list. Chains: INPUT, OUTPUT, FORWARD. Targets: ACCEPT, DROP, REJECT

firewall-cmd
System Control

Firewalld command-line client

Syntax:

firewall-cmd [options]

Examples:

sudo firewall-cmd --list-all

Show firewall configuration

sudo firewall-cmd --add-service=http --permanent

Allow HTTP permanently

sudo firewall-cmd --add-port=8080/tcp --permanent

Open port 8080

sudo firewall-cmd --reload

Reload firewall configuration

Notes:

Front-end for firewalld on RHEL/CentOS/Fedora. Use --permanent for persistent rules, then --reload

ufw
System Control

Uncomplicated Firewall - simplified iptables

Syntax:

ufw [options] [rule]

Examples:

sudo ufw status

Check firewall status

sudo ufw enable

Enable firewall

sudo ufw allow 22/tcp

Allow SSH

sudo ufw allow from 192.168.1.0/24

Allow traffic from subnet

sudo ufw deny 80

Block port 80

Notes:

User-friendly firewall on Ubuntu/Debian. Simple syntax. Use 'allow' or 'deny' with port/service names

lsof
System Control

List open files and network connections

Syntax:

lsof [options] [file]

Examples:

lsof

List all open files

lsof -i :80

Show processes using port 80

lsof -u username

List files opened by specific user

lsof -c nginx

List files opened by nginx process

lsof -i -P

List network connections with port numbers

Notes:

Everything is a file in Linux. Use -i for network, -u for user, -c for command, -p for PID

crontab
System Control

Schedule recurring tasks

Syntax:

crontab [options] [file]

Examples:

crontab -e

Edit current user's crontab

crontab -l

List current user's cron jobs

crontab -r

Remove current user's crontab

sudo crontab -u username -e

Edit crontab for specific user

Notes:

Format: minute hour day month weekday command. Use * for any. Example: '0 2 * * * /backup.sh' runs daily at 2am

apt
Package Management

Package manager for Debian/Ubuntu

Syntax:

apt [options] command [package]

Examples:

apt update

Update package list

apt upgrade

Upgrade installed packages

apt install package

Install package

apt remove package

Remove package

apt search keyword

Search for packages

Notes:

Modern replacement for apt-get, requires sudo for most operations

yum
Package Management

Package manager for Red Hat/CentOS

Syntax:

yum [options] command [package]

Examples:

yum update

Update all packages

yum install package

Install package

yum remove package

Remove package

yum search keyword

Search for packages

yum list installed

List installed packages

Notes:

Package manager for RHEL-based systems, being replaced by dnf

dnf
Package Management

Package manager for Fedora/RHEL 8+

Syntax:

dnf [options] command [package]

Examples:

dnf update

Update all packages

dnf install package

Install package

dnf remove package

Remove package

dnf search keyword

Search for packages

dnf history

Show transaction history

Notes:

Modern replacement for yum in Fedora and RHEL 8+

pacman
Package Management

Package manager for Arch Linux

Syntax:

pacman [options] [package]

Examples:

sudo pacman -Syu

Synchronize and update all packages

sudo pacman -S package_name

Install a package

sudo pacman -R package_name

Remove a package

pacman -Q

List all installed packages

Notes:

This is the package manager for Arch Linux and its derivatives.

env
Environment

Display or set environment variables

Syntax:

env [options] [variable=value] [command]

Examples:

env

Display all environment variables

env PATH=/custom/path command

Run command with modified PATH

env -i command

Run command with empty environment

Notes:

Use without arguments to see all environment variables

export
Environment

Set environment variables

Syntax:

export [variable[=value]]

Examples:

export PATH=$PATH:/new/path

Add to PATH variable

export EDITOR=vim

Set default editor

export

Show all exported variables

Notes:

Makes variables available to child processes

echo
Environment

Display text

Syntax:

echo [options] [text]

Examples:

echo 'Hello World'

Print text

echo $PATH

Print environment variable

echo -n 'No newline'

Print without newline

echo -e 'Line 1\nLine 2'

Interpret escape sequences

Notes:

Use -n to suppress newline, -e to enable escape sequences

history
Environment

Display command history

Syntax:

history [options]

Examples:

history

Show command history

history 10

Show last 10 commands

history -c

Clear history

!123

Execute command number 123 from history

Notes:

Use !n to repeat command n, !! for last command, !string for last command starting with string

alias
Environment

Create command aliases

Syntax:

alias [name[=value]]

Examples:

alias ll='ls -la'

Create alias for long listing

alias

Show all aliases

alias grep='grep --color=auto'

Make grep colorful by default

Notes:

Aliases are temporary unless added to shell configuration files

who
User Management

Show who is logged on

Syntax:

who

Examples:

who

Show who is logged on

Notes:

Use 'w' for more detailed information

passwd
User Management

Change user password

Syntax:

passwd [username]

Examples:

passwd

Change your own password.

sudo passwd john

Change password for user 'john'.

Notes:

Requires sudo/root privileges to change another user's password.

adduser
User Management

Add a new user

Syntax:

adduser [username]

Examples:

sudo adduser newuser

Interactively add a new user.

Notes:

A user-friendly, interactive frontend to 'useradd'. Common on Debian/Ubuntu.

groupadd
User Management

Create a new group

Syntax:

groupadd [groupname]

Examples:

sudo groupadd developers

Create a new group called 'developers'.

Notes:

Use 'usermod -aG groupname username' to add a user to a group.

useradd
User Management

Create a new user account

Syntax:

useradd [options] username

Examples:

sudo useradd john

Create new user 'john'

sudo useradd -m -s /bin/bash john

Create user with home directory and bash shell

sudo useradd -G sudo,www-data john

Create user and add to groups

sudo useradd -e 2024-12-31 john

Create user with account expiration date

Notes:

Low-level command. Use -m for home directory, -s for shell, -G for groups. Consider using 'adduser' on Debian/Ubuntu

usermod
User Management

Modify user account

Syntax:

usermod [options] username

Examples:

sudo usermod -aG sudo john

Add user to sudo group

sudo usermod -s /bin/zsh john

Change user's shell

sudo usermod -L john

Lock user account

sudo usermod -U john

Unlock user account

sudo usermod -d /new/home -m john

Change home directory and move contents

Notes:

Use -aG to append groups (without -a removes from other groups), -L to lock, -U to unlock, -s to change shell

gpasswd
User Management

Administer groups

Syntax:

gpasswd [options] group

Examples:

sudo gpasswd -a john developers

Add user to group

sudo gpasswd -d john developers

Remove user from group

sudo gpasswd -A john developers

Make user an admin of the group

gpasswd developers

Set group password (interactive)

Notes:

Use -a to add user, -d to delete user from group, -A to set group admin. More intuitive than usermod for groups

groups
User Management

Display group memberships

Syntax:

groups [username]

Examples:

groups

Show groups for current user

groups john

Show groups for user 'john'

groups john jane

Show groups for multiple users

Notes:

Lists all groups a user belongs to. First group listed is the primary group

🚀 Linux Pro Tips

Essential Keyboard Shortcuts

  • Ctrl+C - Interrupt current command
  • Ctrl+Z - Suspend current process
  • Ctrl+D - Exit current shell/EOF
  • Ctrl+L - Clear screen
  • Ctrl+R - Search command history
  • Tab - Auto-complete commands/paths

Common Command Combinations

  • command | less - Paginate output
  • command > file.txt - Redirect output to file
  • command >> file.txt - Append output to file
  • command 2>&1 - Redirect errors to output
  • command & - Run in background
  • command1 && command2 - Run command2 if command1 succeeds

⚠️ Safety Tips

  • • Always double-check rm commands, especially with -r and -f flags
  • • Use ls to verify paths before running destructive commands
  • • Test commands on non-critical files first
  • • Use sudo carefully - it grants full system access
  • • Make backups before making system changes

📚 Keep Learning

Master Linux with these essential practices:

📖 Read Man Pages

Use man command for detailed documentation

🛠️ Practice Regularly

Use a virtual machine or container for safe practice

🔍 Explore Options

Try command --help for quick option lists