Freebie

Commands reference

This page lists all commands covered in the bash documentation section, organized by category. Each entry includes a brief description, common options, and a real-world usage example. Refer to this page when you need a quick reminder of syntax or flags.

Text processing

awk

A programming language for transforming structured text. Splits each line into fields and runs your program against each line. Fields are numbered $1, $2, …, $NF (last field). $0 is the whole line.

Common options:

OptionDescription
-F:Set field separator to :
-fRead awk program from a file
-vSet a variable before execution

Common usage:

awk '{print $1}' file.txt                           # print first column
awk -F: '{print $1, $7}' /etc/passwd                # usernames and shells from passwd
awk '{sum+=$1} END {print sum}' numbers.txt         # sum the first column
awk '$9 >= 500' /var/log/apache2/access.log         # HTTP 5xx errors
awk '{counts[$1]++} END {for (k in counts) print counts[k], k}' ips.txt  # count by key

cat

Concatenates files and prints them to stdout. Short for “concatenate.”

Common usage:

cat file1.txt file2.txt                 # combine two files
cat -n file.txt                         # print with line numbers
cat /dev/null > file.txt                # empty a file without deleting it

cut

Extracts specific columns from a file.

Common options:

OptionDescription
-f NPrint field N (tab-delimited by default)
-f N-MPrint fields N through M
-c NPrint character N
-c N-MPrint characters N through M
-d ,Set field delimiter to ,

Common usage:

cut -d: -f1 /etc/passwd                 # extract usernames
cut -d: -f1,7 /etc/passwd               # extract usernames and shells
cut -f1-3 report.tsv                    # first three tab-delimited fields
cut -c1-32 checksums.txt                # first 32 characters (md5sum width)

diff

Compares two files line by line and prints their differences.

Common options:

OptionDescription
-uUnified diff format (shows context)
-rRecursively compare directories
-iIgnore case differences
-qReport only whether files differ

Common usage:

diff file1.txt file2.txt                            # basic comparison
diff -u config.old config.new                       # unified diff for reviewing changes
diff -r dir1/ dir2/                                 # compare two directories
diff <(sort file1.txt) <(sort file2.txt)            # compare sorted versions

grep

Searches files for lines matching a pattern and prints each matching line.

Common options:

OptionDescription
-cCount matching lines
-EEnable extended regular expressions
-iIgnore case
-lPrint only filenames with at least one match
-nPrint line number before each match
-oPrint only the matching text
-qSilent mode (exit status only)
-rRecursive search
-RRecursive, following symbolic links
-vInvert match: print non-matching lines
-wMatch whole words only
-PPerl-compatible regular expressions

Common usage:

grep "Failed password" /var/log/auth.log            # find failed SSH logins
grep -c "ERROR" /var/log/app.log                    # count error lines
grep -r "PermitRootLogin" /etc/ssh/                 # search SSH config recursively
grep -v '^#' /etc/nginx/nginx.conf | grep -v '^$'  # non-comment, non-blank lines
grep -E '^(web|db|cache)-[0-9]+' /etc/hosts        # match server naming patterns

Prints the first lines of a file. Defaults to 10 lines.

Common options:

OptionDescription
-n NPrint the first N lines
-c NPrint the first N bytes

Common usage:

head -20 /var/log/syslog                # first 20 lines
ls /bin | head -5                       # first 5 filenames
head -3 access.log | wc -w             # count words in first 3 lines

md5sum

Computes or verifies MD5 checksums for files.

Common options:

OptionDescription
-cVerify checksums from a file

Common usage:

md5sum /etc/passwd                                  # compute hash
md5sum *.txt | cut -d' ' -f1 | sort | uniq -c       # find duplicate files
md5sum -c checksums.md5                             # verify a list of files

paste

Combines files side by side, separating columns with a tab.

Common options:

OptionDescription
-d ,Set column delimiter to ,
-d \nInterleave lines from two files

Common usage:

paste names.txt scores.txt                          # tab-delimited columns
paste -d, first.txt last.txt                        # comma-delimited
paste -d '\n' evens.txt odds.txt                    # interleave lines
paste <(seq 1 5) <(seq 6 10)                        # combine generated sequences

rev

Reverses the characters on each line.

Common usage:

rev /etc/shells | cut -d/ -f1 | rev     # extract last path component from each line
echo "hello" | rev                       # olleh

sed

Transforms text by applying scripts to each line. Most commonly used for substitution.

Common options:

OptionDescription
-iModify the file in place
-eAdd a script to run
-fRead scripts from a file
-nSuppress default output (print only with p)

Common usage:

sed 's/old/new/g' file.txt                          # replace all occurrences
sed -i 's/old-host/new-host/g' config.conf          # in-place replacement
sed '/^#/d' config.conf                             # delete comment lines
sed -n '5,10p' /var/log/syslog                      # print lines 5 through 10
sed -n '/ERROR/p' app.log                           # print error lines only
echo "2025-03-29" | sed 's/\([0-9]*\)-\([0-9]*\)-\([0-9]*\)/\3\/\2\/\1/'  # reformat date

sha1sum

Computes or verifies SHA-1 checksums for files.

Common options:

OptionDescription
-cVerify checksums from a file

Common usage:

sha1sum /etc/ssh/sshd_config                        # compute a hash before editing
sha1sum deployment.tar.gz                           # verify a downloaded archive
sha1sum -c published_checksums.txt                  # batch verification

sort

Sorts lines of a file.

Common options:

OptionDescription
-rReverse order
-nNumeric sort
-nrNumeric descending
-uRemove duplicates
-fIgnore case
-k NSort by field N
-t ,Set field delimiter to ,
-oWrite output to a file

Common usage:

sort /etc/hosts                                     # alphabetical sort
sort -rn numbers.txt                                # numeric descending
sort -k3 access.log                                 # sort by third field
sort -u /var/log/ips.txt                            # sorted, unique IPs
cut -f1 grades | sort | uniq -c | sort -rn          # grade frequency analysis

tac

Prints files in reverse line order (bottom to top). The name is cat spelled backwards.

Common usage:

tac /var/log/apache2/access.log | head -20          # most recent 20 log entries
tac changelog.txt                                   # read a changelog newest-first

tail

Prints the last lines of a file. Defaults to 10 lines.

Common options:

OptionDescription
-n NPrint the last N lines
-n +NPrint starting at line N
-fFollow the file as new lines are written
-FFollow by filename (handles log rotation)

Common usage:

tail -f /var/log/nginx/error.log                    # live log monitoring
tail -n 50 /var/log/syslog                          # last 50 lines
tail -n +3 /etc/hosts                               # from line 3 to end
tail -F /var/log/app.log                            # follow through log rotation

tr

Translates or deletes characters.

Common options:

OptionDescription
-dDelete characters in the first set
-sSqueeze repeated characters to one

Common usage:

echo $PATH | tr ':' '\n'                            # print PATH entries one per line
echo "HELLO" | tr '[A-Z]' '[a-z]'                   # convert to lowercase
echo "hello world" | tr -d ' '                      # remove spaces
echo "a   b" | tr -s ' '                            # squeeze multiple spaces to one

uniq

Filters adjacent duplicate lines. Always sort input first.

Common options:

OptionDescription
-cPrefix each line with its occurrence count
-dPrint only lines that appear more than once
-uPrint only lines that appear exactly once
-iIgnore case

Common usage:

sort ips.txt | uniq                                 # unique IP addresses
sort access.log | uniq -c | sort -rn                # most frequent log entries
awk '{print $9}' access.log | sort | uniq -c | sort -rn | head  # HTTP status codes

wc

Counts lines, words, and characters.

Common options:

OptionDescription
-lCount lines only
-wCount words only
-cCount characters only

Common usage:

wc -l /var/log/auth.log                             # line count
wc -w /etc/nginx/nginx.conf                         # word count
ls -1 /etc | wc -l                                  # number of entries in a directory
grep "ERROR" app.log | wc -l                        # count error lines

File system

cd

Changes the current working directory. A built-in command.

Common usage:

cd /var/log                     # absolute path
cd ..                           # parent directory
cd -                            # previous directory
cd                              # home directory
cd ~user                        # home directory of another user

chmod

Changes file or directory permissions.

Common options:

OptionDescription
-RRecursive
+xAdd execute permission
755Set owner rwx, group rx, other rx
644Set owner rw, group r, other r

Common usage:

chmod +x deploy.sh                                  # make a script executable
chmod 755 /usr/local/bin/myscript                   # standard executable permissions
chmod 644 /etc/app/config.conf                      # standard config file permissions
chmod -R 750 /var/app/                              # recursive, owner and group only

chown

Changes file owner and group.

Common options:

OptionDescription
-RRecursive

Common usage:

chown alice file.txt                                # change owner to alice
chown alice:developers project/                     # change owner and group
chown -R www-data:www-data /var/www/html/           # fix web server file ownership

chgrp

Changes the group ownership of a file.

Common usage:

chgrp developers /var/app/config.conf
chgrp -R staff /shared/docs/

cp

Copies files and directories.

Common options:

OptionDescription
-rRecursive (for directories)
-aArchive mode: preserve permissions, timestamps, and links
-iPrompt before overwriting
-pPreserve file attributes

Common usage:

cp config.conf config.conf.bak                      # back up a file before editing
cp -a /var/www/html/ /var/www/html.backup/          # archive copy of a directory
cp -r /etc/app/ /tmp/app_backup/                    # recursive copy

df

Reports filesystem disk space usage.

Common options:

OptionDescription
-hHuman-readable sizes
-TShow filesystem type

Common usage:

df -h                                               # all mounted filesystems
df -h /var                                          # usage for a specific mount
df -h / | awk 'NR==2 {print $5}'                    # root disk usage percentage

find

Searches directory trees for files matching criteria.

Common options:

OptionDescription
-nameMatch by filename (supports globs)
-type fRegular files only
-type dDirectories only
-size +100MFiles larger than 100 MB
-mtime -1Modified within 24 hours
-mtime +7Modified more than 7 days ago
-exec cmd {} \;Run a command on each result
-deleteDelete matching files

Common usage:

find /etc -name "*.conf" -type f                    # config files in /etc
find /var -size +50M                                # large files
find /home -mtime -1 -type f                        # files changed today
find /tmp -type f -mtime +7 -delete                 # clean up old temp files
find / -name "authorized_keys" 2>/dev/null          # locate SSH authorized key files

ls

Lists directory contents.

Common options:

OptionDescription
-lLong format (permissions, owner, size, date)
-aInclude hidden files
-hHuman-readable sizes with -l
-tSort by modification time, newest first
-rReverse sort order
-1Force one entry per line
-SSort by file size

Common usage:

ls -lh /var/log                                     # long listing with sizes
ls -lt /etc | head -10                              # 10 most recently modified files
ls -la ~                                            # all files including hidden
ls -1 /etc | wc -l                                  # count files in a directory

mkdir

Creates directories.

Common options:

OptionDescription
-pCreate parent directories as needed

Common usage:

mkdir /var/app/logs                                 # create a directory
mkdir -p /var/app/{logs,config,data}                # create multiple directories with parents
mkdir -p deploy/{staging,production}/configs        # nested structure in one command

mv

Moves or renames files and directories.

Common options:

OptionDescription
-iPrompt before overwriting
-nDo not overwrite existing files

Common usage:

mv config.conf config.conf.bak                      # rename a file
mv *.log /var/archive/                              # move files to another directory
mv /tmp/new_config.conf /etc/app/config.conf        # deploy a new config

rm

Removes files and directories.

Common options:

OptionDescription
-rRecursive (required for directories)
-fForce: no prompts, ignore non-existent files
-iPrompt before each deletion

Common usage:

rm old_report.txt                                   # delete a file
rm -i *.tmp                                         # delete with confirmation
rm -rf /tmp/build_cache/                            # force-delete a directory tree

tar

Creates and extracts archive files.

Common options:

OptionDescription
-cCreate archive
-xExtract archive
-zCompress or decompress with gzip
-fSpecify the archive filename
-tList archive contents without extracting
-vVerbose output

Common usage:

tar -czf backup.tar.gz /var/www/html/               # create a compressed archive
tar -xzf backup.tar.gz                              # extract
tar -tzf backup.tar.gz                              # list contents
tar -czf "${HOSTNAME}_logs_$(date +%Y%m%d).tar.gz" /var/log   # timestamped log archive

touch

Creates empty files or updates the modification timestamp of existing files.

Common usage:

touch new_file.txt                                  # create an empty file
touch -t 202501010000 file.txt                      # set a specific timestamp
touch file{0..999}.txt                              # create 1000 empty files at once

Processes

bg

Resumes a suspended job in the background.

Common usage:

bg                  # resume the most recently suspended job
bg %2               # resume job number 2

fg

Brings a background or suspended job to the foreground.

Common usage:

fg                  # foreground the most recent job
fg %1               # foreground job number 1

jobs

Lists all jobs running in the current shell.

Common usage:

jobs                # list jobs with status
jobs -l             # include process IDs

kill

Sends a signal to a process.

Common options:

OptionDescription
-9SIGKILL: force-terminate immediately
-15SIGTERM: polite termination (default)
-lList all signal names

Common usage:

kill 12345                      # send SIGTERM to process 12345
kill -9 12345                   # force-kill
kill %1                         # kill background job 1
kill -l                         # list all signals

ps

Reports information about running processes.

Common options:

OptionDescription
auxAll processes with user, CPU, and memory usage
-efAll processes in full format
-fFull listing for current user

Common usage:

ps aux                                              # all processes
ps aux | grep nginx                                 # find nginx processes
ps aux --sort=-%mem | head -10                      # top 10 by memory usage
ps -ef | grep "[p]ython"                            # find Python processes (brackets avoid matching grep itself)

sleep

Pauses script execution for a specified duration.

Common usage:

sleep 5                         # pause for 5 seconds
sleep 0.5                       # pause for half a second
sleep 2h                        # pause for 2 hours (suffixes: s, m, h, d)

Networking

arp

Displays and manipulates the ARP cache (Address Resolution Protocol).

Common usage:

arp -a                          # display the ARP table

curl

Transfers data from or to a server. Prints output to stdout by default.

Common options:

OptionDescription
-OSave output to a file using the remote filename
-oSave output to a specified file
-sSilent: suppress progress output
-LFollow redirects
-IFetch headers only

Common usage:

curl https://example.com/api/health                 # check an endpoint
curl -O https://example.com/file.tar.gz             # download a file
curl -s https://api.example.com/status | jq .       # parse JSON response
curl -I https://example.com                         # inspect response headers

ip

Queries and configures network interfaces and routes. Replaces the older ifconfig and route commands.

Common usage:

ip addr show                            # list all interfaces and IP addresses
ip addr show eth0                       # show a specific interface
ip route                                # display the routing table
ip link show                            # show link status for all interfaces

netstat

Displays network connections, routing tables, and interface statistics. On modern systems, ss is a faster alternative.

Common options:

OptionDescription
-aAll connections and listening sockets
-nNumeric addresses (skip DNS resolution)
-tTCP connections only
-uUDP connections only
-pShow process name and PID

Common usage:

netstat -an | grep :80                              # connections on port 80
netstat -tlnp                                       # listening TCP ports with process info
ss -tlnp                                            # modern equivalent with ss

scp

Copies files between hosts over SSH.

Common options:

OptionDescription
-rRecursive
-pPreserve timestamps and permissions

Common usage:

scp file.txt user@host:/tmp/                        # copy to remote machine
scp user@host:/var/log/app.log /tmp/                # copy from remote machine
scp -r ./configs/ user@host:/etc/app/               # recursive copy

ssh

Opens a secure shell connection to a remote host.

Common options:

OptionDescription
-TSuppress pseudo-terminal output
-iSpecify identity (key) file
-pSpecify port

Common usage:

ssh user@host                                       # interactive session
ssh user@host ps aux                                # run a single command
ssh user@host bash < ./deploy.sh                    # run a local script remotely
echo "df -h" | ssh -T user@host                     # pipe a command to SSH

wget

Downloads files from the web and saves them to disk.

Common options:

OptionDescription
-qQuiet mode
-OSave to a specified filename
-rRecursive download
--limit-rateLimit download speed

Common usage:

wget https://example.com/file.tar.gz                # download a file
wget -q -O /tmp/status.json https://api.example.com/status  # quiet, custom filename

System information

cal

Displays a calendar.

Common usage:

cal                     # current month
cal 2025                # full year calendar
cal 3 2025              # March 2025

date

Prints or sets the system date and time.

Common usage:

date                                    # current date and time
date +%Y-%m-%d                          # ISO 8601 date
date +%s                                # Unix epoch timestamp
date --date "2 weeks ago" +%Y-%m-%d     # date relative to today

iostat

Reports CPU and I/O statistics.

Common usage:

iostat                          # summary since boot
iostat 2 5                      # report every 2 seconds, 5 times

last

Shows login history by reading the /var/log/wtmp file.

Common usage:

last                            # all logins
last -n 20                      # last 20 logins
last alice                      # login history for user alice
last reboot                     # system reboots

mount

Lists mounted filesystems or mounts a filesystem.

Common usage:

mount                           # list all mounted filesystems
mount | grep /var               # check if /var is mounted

sar

Collects and reports system activity statistics. Requires the sysstat package.

Common usage:

sar 1 5                         # CPU usage every second, 5 times
sar -r 1 5                      # memory usage
sar -d 1 5                      # disk activity

uname

Prints system information.

Common options:

OptionDescription
-aAll available information
-rKernel release only
-mMachine hardware name

Common usage:

uname -a                        # full system information
uname -r                        # kernel version

vmstat

Reports virtual memory, processes, and CPU activity.

Common usage:

vmstat                          # snapshot
vmstat 2 5                      # report every 2 seconds, 5 times

w

Displays who is logged in and what they are doing. An extended version of who that also shows uptime.

Common usage:

w                               # logged-in users with activity
w alice                         # activity for a specific user

who

Shows who is currently logged in to the system.

Common usage:

who                             # current users
who am i                        # your own login info: name, terminal, login time, and origin

whoami

Prints your current username.

Common usage:

whoami                          # useful in scripts to check if running as root
[ "$(whoami)" = "root" ] || { echo "Must run as root" >&2; exit 1; }

Shell utilities

alias

Creates or lists command shortcuts.

Common usage:

alias                           # list all aliases
alias ll="ls -lh"               # define an alias
alias rm="rm -i"                # safer rm
unalias ll                      # remove an alias

export

Marks a variable as an environment variable, making it available to child processes.

Common usage:

export PATH=$HOME/bin:$PATH     # extend PATH
export DB_HOST=db.internal      # pass configuration to scripts
export EDITOR=vim               # set default editor

history

Lists commands previously run in the current shell.

Common usage:

history                         # all history
history 20                      # last 20 commands
history | grep ssh              # filter history
history -c                      # clear history

printenv

Prints environment variables.

Common usage:

printenv                        # all environment variables
printenv PATH                   # a specific variable
printenv | sort                 # sorted listing

read

Reads a line from stdin and stores it in a variable.

Common options:

OptionDescription
-pDisplay a prompt string
-sSilent (do not echo input)
-aRead into an array
-rRaw mode (do not interpret backslashes)
-t NTime out after N seconds

Common usage:

read -p "Enter hostname: " HOST
read -s -p "Password: " PASS
readarray -t LINES < /etc/hosts

seq

Generates a sequence of numbers.

Common usage:

seq 1 10                        # 1 to 10
seq 0 2 20                      # 0, 2, 4, ... 20
seq -w 1 10                     # zero-padded: 01, 02, ... 10
seq -s, 1 5                     # 1,2,3,4,5 (comma-separated)

set

Displays all shell variables and functions, or controls shell options.

Common usage:

set                             # list all variables
set -x                          # enable debug output (trace commands)
set +x                          # disable debug output
set -e                          # exit on error
set -u                          # treat unset variables as errors

source

Runs a script in the current shell rather than a child process. Changes to variables and the environment take effect in your current shell.

Common usage:

source ~/.bashrc                # reload shell configuration
source ./env.sh                 # load environment variables into current shell
. ~/.bashrc                     # shorthand for source

type

Identifies how the shell will interpret a command: as a file, built-in, alias, or keyword.

Common usage:

type ls                         # ls is /usr/bin/ls
type cd                         # cd is a shell builtin
type ll                         # ll is aliased to `ls -lh`
type if                         # if is a shell keyword
type -t cat                     # print type only: "file"

which

Locates the executable file that the shell will run for a given command.

Common usage:

which python3                   # /usr/bin/python3
which bash                      # /usr/bin/bash

xargs

Builds and executes commands from stdin.

Common options:

OptionDescription
-n NPass at most N arguments per command
-I {}Use {} as a placeholder for each input string
-0Read null-delimited input (use with find -print0)
-P NRun N processes in parallel

Common usage:

find . -name "*.py" -print0 | xargs -0 wc -l           # line count across all Python files
cat servers.txt | xargs -I {} ssh {} uptime             # run uptime on each server
find . -name "*.log" -print0 | xargs -0 grep "ERROR"   # search logs with null separators
ls *.jpg | xargs -n1 -I {} convert {} -resize 800x {}_thumb.jpg  # batch image resize

User and permissions

chgrp

Changes the group ownership of a file.

Common usage:

chgrp developers /var/app/                          # change group
chgrp -R staff /shared/docs/                        # recursive

passwd

Changes a user’s password.

Common usage:

passwd                          # change your own password
sudo passwd alice               # change another user's password (as root)