$ Linux Commands

All Commands (74)

apt Package Management

Advanced Package Tool — Debian/Ubuntu package manager

apt COMMAND [PACKAGE]
sudo apt update
sudo apt upgrade
sudo apt install nginx
sudo apt remove nginx
sudo apt autoremove
sudo apt search python3
update refresh package index
upgrade upgrade all packages
install install a package
remove remove a package
autoremove remove unused dependencies
search search for packages
show show package details

Always run apt update before install to get the latest package list.

apt-get Package Management

Classic APT command-line tool

apt-get COMMAND [PACKAGE]
sudo apt-get update
sudo apt-get install python3
sudo apt-get remove python3
sudo apt-get purge python3
update refresh package list
install install package
remove remove package (keep config)
purge remove package and config files

apt is the modern user-friendly version; apt-get is better for scripts.

awk Text Processing

Pattern scanning and processing language

awk 'PROGRAM' [FILE...]
awk '{print $1}' file.txt
awk -F: '{print $1}' /etc/passwd
awk '{sum += $1} END {print sum}' nums.txt
-F set field separator

$1, $2... refer to fields. $0 is the whole line. NR is the line number.

cat File Management

Concatenate and display file contents

cat [OPTIONS] FILE...
cat file.txt
cat file1.txt file2.txt > combined.txt
cat -n file.txt
-n number all output lines
-A show non-printing characters
cd File Management

Change the current directory

cd [PATH]
cd /home/alice
cd ~
cd ..
cd -

cd - returns to the previous directory. cd ~ goes to your home directory.

chmod Permissions

Change file permissions

chmod [OPTIONS] MODE FILE...
chmod 755 script.sh
chmod +x script.sh
chmod -R 644 /var/www/html
chmod u+w file.txt
-R apply recursively

Octal: 7=rwx 6=rw- 5=r-x 4=r-- 0=---. Common: 755 for dirs/executables, 644 for files.

chown Permissions

Change file owner and group

chown [OPTIONS] OWNER[:GROUP] FILE...
chown alice file.txt
chown alice:www-data /var/www/html
chown -R alice:www-data /home/alice/myapp
-R apply recursively
cp File Management

Copy files or directories

cp [OPTIONS] SOURCE DEST
cp file.txt backup.txt
cp -r /src/dir /dest/dir
cp -i file.txt /tmp/
-r copy directories recursively
-i prompt before overwriting
-u copy only when source is newer
-v verbose output
curl Networking

Transfer data from or to a server

curl [OPTIONS] URL
curl https://example.com
curl -o file.zip https://example.com/file.zip
curl -I https://example.com
curl -X POST -d '{"key":"val"}' -H "Content-Type: application/json" https://api.example.com
-o FILE save to file
-O save with remote filename
-I headers only
-L follow redirects
-s silent mode
-X METHOD set HTTP method
-d DATA POST data
-H add header
cut Text Processing

Remove sections from each line of input

cut [OPTIONS] [FILE...]
cut -d: -f1 /etc/passwd
cut -c1-10 file.txt
-d delimiter
-f field numbers
-c character positions
date System Info

Display or set the system date and time

date [OPTIONS] [+FORMAT]
date
date +"%Y-%m-%d"
date +"%H:%M:%S"
df System Info

Report disk space usage of filesystems

df [OPTIONS] [FILE...]
df -h
df -h /
df -T
-h human-readable sizes
-T show filesystem type
-i show inode info instead
diff Text Processing

Compare files line by line

diff [OPTIONS] FILE1 FILE2
diff file1.txt file2.txt
diff -u old.py new.py
-u unified format (easier to read)
-r compare directories recursively
-i ignore case
du Disk Usage

Estimate file and directory space usage

du [OPTIONS] [PATH]
du -sh /var/log
du -sh *
du -h --max-depth=1 /home
-s summary total only
-h human-readable
--max-depth N limit depth
-a all files, not just directories

du -sh * in a directory gives you a quick size overview of each item.

find File Management

Search for files in a directory hierarchy

find PATH [OPTIONS] [EXPRESSION]
find . -name "*.py"
find /var/log -name "*.log" -mtime -7
find . -type d
find . -size +10M
-name match by filename
-type f=file, d=directory
-mtime modified N days ago
-size match by size
-exec run command on results

Use -exec rm {} \; to delete found files, or pipe to xargs for efficiency.

free System Info

Display amount of free and used memory

free [OPTIONS]
free -h
free -m
-h human-readable
-m display in megabytes
-g display in gigabytes
-s N repeat every N seconds
grep Text Processing

Search text using patterns

grep [OPTIONS] PATTERN [FILE...]
grep "error" /var/log/syslog
grep -r "TODO" ./src
grep -i "warning" app.log
grep -n "def " app.py
-r recursive search
-i case-insensitive
-n show line numbers
-l only print filenames
-v invert match
-c count matches
-E extended regex
groups User Management

Show group memberships for a user

groups [USER]
groups
groups alice
gzip Archiving

Compress files using gzip

gzip [OPTIONS] FILE
gzip file.txt
gzip -d file.txt.gz
gzip -k file.txt
-d decompress
-k keep original file
-9 best compression
-1 fastest compression
head File Management

Output the first lines of a file

head [OPTIONS] FILE
head file.txt
head -n 20 file.txt
-n N print first N lines (default 10)
hostname System Info

Show or set the system hostname

hostname [OPTIONS] [NAME]
hostname
hostname -I
hostname -f
-I all IP addresses
-f FQDN (fully qualified domain name)
htop Process Management

Interactive process viewer (enhanced top)

htop
htop

Install with: sudo apt install htop. Use F9 to kill, F6 to sort, F5 for tree view.

id Permissions

Print user and group information

id [USER]
id
id alice
ip Networking

Show and manipulate network interfaces and routing

ip [OPTIONS] OBJECT COMMAND
ip addr
ip addr show eth0
ip route
ip link
addr IP addresses
route routing table
link network interfaces
journalctl Process Management

Query the systemd journal (logs)

journalctl [OPTIONS] [MATCHES]
journalctl -u nginx
journalctl -u myapp -n 50
journalctl -u myapp -f
journalctl --since "1 hour ago"
-u UNIT show logs for a service
-n N show last N lines
-f follow (live output)
-r newest first
--since filter by date/time
kill Process Management

Send a signal to a process

kill [OPTIONS] PID
kill 1234
kill -9 1234
kill -SIGTERM 1234
-9 / -SIGKILL force kill immediately
-15 / -SIGTERM graceful shutdown (default)

Get the PID from ps aux or pgrep. Use -9 only if graceful shutdown fails.

last User Management

Show listing of last logged-in users

last [OPTIONS] [USER]
last
last alice
last reboot
-n N show last N entries
less File Management

View file contents one screen at a time

less FILE
less /var/log/syslog
less +F /var/log/nginx/error.log
+F follow mode (like tail -f)

Press q to quit, / to search, n for next match, G to jump to end.

ln File Management

Create hard or symbolic links

ln [OPTIONS] TARGET LINK_NAME
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
ln file.txt hardlink.txt
-s create a symbolic (soft) link

Symlinks point to a path; hard links point to the same inode. Use -s for most cases.

ls File Management

List directory contents

ls [OPTIONS] [PATH]
ls
ls -la
ls -lh /var/log
ls -lt
-l long listing format
-a show hidden files
-h human-readable sizes
-t sort by modification time
-r reverse sort order
-S sort by file size

Use ls -la to see all files including hidden ones with full details.

lsblk System Info

List information about block devices

lsblk [OPTIONS]
lsblk
lsblk -f
-f show filesystem info
-o specify output columns
lscpu System Info

Display information about the CPU architecture

lscpu
lscpu
lsof Disk Usage

List open files and the processes using them

lsof [OPTIONS]
lsof -i :80
lsof -u alice
lsof /var/log/syslog
-i PORT files using a network port
-u USER files opened by user
-p PID files opened by process

Useful to find what process is using a port: lsof -i :8080

mkdir File Management

Create directories

mkdir [OPTIONS] DIR...
mkdir mydir
mkdir -p /var/myapp/logs
mkdir -m 755 public
-p create parent directories as needed
-m set permissions (octal)
mount Disk Usage

Mount a filesystem

mount [OPTIONS] DEVICE MOUNTPOINT
mount /dev/sdb1 /mnt/usb
mount -t ntfs /dev/sdb1 /mnt/usb
mount | grep sdb
-t TYPE filesystem type (ext4, ntfs, vfat)
-o opts mount options (ro, rw)
mv File Management

Move or rename files and directories

mv [OPTIONS] SOURCE DEST
mv old.txt new.txt
mv file.txt /tmp/
mv -i file.txt /tmp/
-i prompt before overwriting
-v verbose output

mv is also how you rename files — just move to a new name in the same directory.

netstat Networking

Print network connections and statistics

netstat [OPTIONS]
netstat -tulpn
netstat -an | grep :80
-t TCP connections
-u UDP connections
-l listening sockets
-p show PID/program name
-n numeric addresses (no DNS lookup)

ss is a modern replacement for netstat and is faster.

nmap Networking

Network exploration and port scanning tool

nmap [OPTIONS] HOST
nmap 192.168.1.1
nmap -p 80,443 example.com
nmap -sV example.com
-p PORTS scan specific ports
-sV detect service versions
-O OS detection
-A aggressive scan (OS, version, scripts)

Only scan networks you have permission to scan.

nohup Process Management

Run a command immune to hangups

nohup COMMAND [ARGS] &
nohup python script.py &
nohup ./server.sh > output.log 2>&1 &

Output goes to nohup.out by default. Use & to run in the background.

passwd User Management

Change a user password

passwd [USERNAME]
passwd
sudo passwd alice

Running passwd without a username changes your own password.

pgrep Process Management

Find processes by name

pgrep [OPTIONS] PATTERN
pgrep nginx
pgrep -l python
-l show process name alongside PID
-u USER filter by user
ping Networking

Send ICMP ECHO_REQUEST packets to a host

ping [OPTIONS] HOST
ping google.com
ping -c 4 google.com
ping -i 0.5 google.com
-c N stop after N packets
-i N interval between packets (seconds)
pip Package Management

Python package installer

pip install [OPTIONS] PACKAGE
pip install flask
pip install -r requirements.txt
pip list
pip freeze > requirements.txt
pip uninstall flask
install install package
uninstall remove package
list list installed packages
freeze output installed packages
-r FILE install from requirements file
--upgrade upgrade a package

Always use pip inside a virtual environment (venv) to avoid system conflicts.

pip3 Package Management

Python 3 package installer

pip3 install [OPTIONS] PACKAGE
pip3 install flask gunicorn
pip3 install -r requirements.txt
pip3 freeze > requirements.txt
Same flags as pip

Use pip3 explicitly when both Python 2 and 3 are installed.

pkill Process Management

Kill processes by name

pkill [OPTIONS] PATTERN
pkill nginx
pkill -9 python
-9 force kill
-u USER only kill that user's processes
ps Process Management

Report a snapshot of current processes

ps [OPTIONS]
ps aux
ps aux | grep nginx
ps -ef
aux all processes with user and CPU/mem
-ef full listing, all users

Pipe to grep to find a specific process: ps aux | grep python

pwd File Management

Print working directory (current path)

pwd
pwd
rm File Management

Remove files or directories

rm [OPTIONS] FILE...
rm file.txt
rm -rf /tmp/mydir
rm -i *.log
-r remove directories recursively
-f force, no prompts
-i prompt before each removal
-v verbose

Be careful with rm -rf — it deletes without confirmation and cannot be undone.

scp Networking

Securely copy files between hosts

scp [OPTIONS] SOURCE DEST
scp file.txt user@host:/tmp/
scp user@host:/var/log/app.log .
scp -r ./mydir user@host:/home/user/
-r copy recursively
-P PORT port number
-i FILE identity file
screen Process Management

Terminal multiplexer — keep sessions alive after disconnect

screen [OPTIONS] [COMMAND]
screen -S mysession
screen -r mysession
screen -ls
-S NAME name the session
-r NAME reattach to a session
-ls list sessions

Inside screen: Ctrl+A then D to detach. Ctrl+A then K to kill.

sed Text Processing

Stream editor for filtering and transforming text

sed [OPTIONS] SCRIPT [FILE...]
sed 's/foo/bar/g' file.txt
sed -i 's/old/new/g' file.txt
sed -n '5,10p' file.txt
-i edit file in-place
-n suppress default output
s/old/new/g substitute all occurrences

The -i flag modifies the file directly — always back up first or test without -i.

sort Text Processing

Sort lines of text

sort [OPTIONS] [FILE...]
sort file.txt
sort -r file.txt
sort -n numbers.txt
sort -u file.txt
-r reverse order
-n numeric sort
-u remove duplicates
-k N sort by field N
-t set field delimiter
ss Networking

Investigate sockets (modern netstat replacement)

ss [OPTIONS]
ss -tulpn
ss -an | grep :80
-t TCP
-u UDP
-l listening
-p show processes
-n numeric
ssh Networking

OpenSSH remote login client

ssh [OPTIONS] [USER@]HOST
ssh alice@example.com
ssh -p 2222 user@host
ssh -i ~/.ssh/key.pem user@host
-p PORT connect to specific port
-i FILE identity (private key) file
-L local port forwarding
-v verbose (for debugging)
su Permissions

Switch user

su [OPTIONS] [USER]
su -
su - alice
- start a login shell (loads the user's environment)
sudo Permissions

Execute a command as another user (default: root)

sudo [OPTIONS] COMMAND
sudo apt update
sudo systemctl restart nginx
sudo -u postgres psql
-u USER run as specified user
-i open an interactive root shell
-l list allowed commands
systemctl Process Management

Control the systemd system and service manager

systemctl COMMAND [UNIT]
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl status nginx
sudo systemctl enable nginx
sudo systemctl disable nginx
sudo systemctl daemon-reload
start start a service
stop stop a service
restart restart a service
status show service status
enable start on boot
disable do not start on boot
daemon-reload reload unit files
tail File Management

Output the last lines of a file

tail [OPTIONS] FILE
tail file.txt
tail -n 50 /var/log/syslog
tail -f /var/log/nginx/access.log
-n N print last N lines (default 10)
-f follow: output appended data as file grows

tail -f is essential for watching live log output.

tar Archiving

Archive files (tape archive)

tar [OPTIONS] FILE...
tar -czvf archive.tar.gz /path/to/dir
tar -xzvf archive.tar.gz
tar -tzvf archive.tar.gz
tar -xzvf archive.tar.gz -C /dest/
-c create archive
-x extract archive
-t list contents
-z gzip compression
-j bzip2 compression
-v verbose
-f specify filename
-C extract to directory

Memory aid: "eXtract Ze Files" for xzf. "Create Ze Files" for czf.

top Process Management

Display Linux processes in real time

top
top
top -u alice
-u USER show only that user's processes

Press q to quit, k to kill a process, M to sort by memory, P to sort by CPU.

touch File Management

Create an empty file or update timestamps

touch FILE...
touch newfile.txt
touch file1.txt file2.txt
umask Permissions

Set default permissions for new files

umask [MASK]
umask
umask 022

umask 022 means new files get 644, new dirs get 755.

umount Disk Usage

Unmount a filesystem

umount MOUNTPOINT|DEVICE
umount /mnt/usb
umount /dev/sdb1
-f force unmount
-l lazy unmount (detach when not busy)
uname System Info

Print system information

uname [OPTIONS]
uname -a
uname -r
uname -m
-a all information
-r kernel release
-m machine hardware name
-n hostname
unzip Archiving

Extract compressed files from a ZIP archive

unzip [OPTIONS] ZIPFILE
unzip archive.zip
unzip archive.zip -d /dest/
unzip -l archive.zip
-d DIR extract to directory
-l list contents without extracting
uptime System Info

Show how long the system has been running

uptime
uptime

Shows current time, uptime duration, number of logged-in users, and load averages.

useradd User Management

Create a new user

useradd [OPTIONS] USERNAME
sudo useradd -m -s /bin/bash newuser
sudo useradd -m -G sudo newuser
-m create home directory
-s SHELL set login shell
-G GROUP add to supplementary groups
-d DIR set home directory

After creating a user, set a password with: sudo passwd USERNAME

userdel User Management

Delete a user account

userdel [OPTIONS] USERNAME
sudo userdel alice
sudo userdel -r alice
-r remove home directory and mail spool
usermod User Management

Modify a user account

usermod [OPTIONS] USERNAME
sudo usermod -aG sudo alice
sudo usermod -aG www-data alice
sudo usermod -s /bin/bash alice
-aG GROUP append to group (always use -a with -G)
-s SHELL change login shell
-d DIR change home directory
-l NAME change username

Always use -a with -G to append — without -a it replaces all groups.

w User Management

Show who is logged in and what they are doing

w [USER]
w
w alice

More detailed than who — shows CPU usage and current command.

wc Text Processing

Count lines, words, and characters

wc [OPTIONS] [FILE...]
wc -l file.txt
wc -w file.txt
grep "error" log.txt | wc -l
-l count lines
-w count words
-c count bytes
-m count characters
wget Networking

Non-interactive network downloader

wget [OPTIONS] URL
wget https://example.com/file.zip
wget -O output.zip https://example.com/file.zip
wget -r https://example.com
-O FILE save to specific filename
-r recursive download
-q quiet mode
-c continue interrupted download
who User Management

Show who is logged in

who [OPTIONS]
who
who -b
-b show time of last system boot
zip Archiving

Package and compress files

zip [OPTIONS] ZIPFILE FILE...
zip archive.zip file1.txt file2.txt
zip -r archive.zip /path/to/dir
-r recursive
-e encrypt with password
-9 best compression