Bash
Bash

File & Directory Operations

Create a new directory with the specified name

$mkdir <directory>

Create nested directories, creating parent directories as needed

$mkdir -p <path>

Create a directory with specific permissions

$mkdir -m <mode> <directory>

Remove an empty directory

$rmdir <directory>

Remove a directory and its empty parent directories

$rmdir -p <path>

Delete a file permanently

$rm <file>

Recursively delete a directory and all its contents

$rm -r <directory>

Forcefully delete a file without prompting

$rm -f <file>

Forcefully and recursively delete a directory without prompting

$rm -rf <directory>

Delete a file but prompt for confirmation first

$rm -i <file>

Delete a file and print each action verbosely

$rm -v <file>

Copy a file from source to destination

$cp <source> <destination>

Recursively copy a directory and its contents

$cp -r <source> <destination>

Copy a file preserving its permissions, timestamps, and ownership

$cp -p <source> <destination>

Copy a file but prompt before overwriting existing files

$cp -i <source> <destination>

Copy a file and print each action verbosely

$cp -v <source> <destination>

Copy a file only if source is newer than destination

$cp -u <source> <destination>

Archive copy, preserving all attributes and structure recursively

$cp -a <source> <destination>

Move or rename a file or directory

$mv <source> <destination>

Move a file but prompt before overwriting existing files

$mv -i <source> <destination>

Forcefully move a file without prompting

$mv -f <source> <destination>

Move a file and print each action verbosely

$mv -v <source> <destination>

Move a file but do not overwrite any existing destination

$mv -n <source> <destination>

Create an empty file or update its timestamps

$touch <file>

Set a specific timestamp on a file

$touch -t <timestamp> <file>

Update only the access time of a file

$touch -a <file>

Update only the modification time of a file

$touch -m <file>

Create a hard link to a file

$ln <source> <link>

Create a symbolic (soft) link to a file or directory

$ln -s <source> <link>

Forcefully create a symbolic link, overwriting existing links

$ln -sf <source> <link>

Print the target path a symbolic link points to

$readlink <link>

Print the canonicalized absolute path of a symbolic link

$readlink -f <link>

File Viewing & Editing

Print the contents of a file to standard output

$cat <file>

Print file contents with line numbers

$cat -n <file>

Print file contents showing non-printing characters

$cat -A <file>

Concatenate and print multiple files

$cat <file1> <file2>

Create a new file and write from standard input

$cat > <file>

Append standard input to the end of a file

$cat >> <file>

View file contents with scrollable pagination

$less <file>

View file contents with line numbers in less

$less -N <file>

Open a file and follow it for real-time updates

$less +F <file>

View file contents one screen at a time

$more <file>

Print the first 10 lines of a file

$head <file>

Print the first <n> lines of a file

$head -n <n> <file>

Print the first <n> bytes of a file

$head -c <n> <file>

Print the last 10 lines of a file

$tail <file>

Print the last <n> lines of a file

$tail -n <n> <file>

Follow a file and print new lines as they are appended

$tail -f <file>

Follow a file by name, re-opening if it is rotated

$tail -F <file>

Print the last <n> bytes of a file

$tail -c <n> <file>

Open a file in the nano terminal text editor

$nano <file>

Open a file in the vim terminal text editor

$vim <file>

Open a file in the vi terminal text editor

$vi <file>

Open a file in the GNOME graphical text editor

$gedit <file>

Count lines, words, and bytes in a file

$wc <file>

Count only the number of lines in a file

$wc -l <file>

Count only the number of words in a file

$wc -w <file>

Count only the number of bytes in a file

$wc -c <file>

Count the number of characters in a file

$wc -m <file>

Search & Find

Find files matching a name pattern in a directory tree

$find <path> -name <pattern>

Find only regular files within a directory tree

$find <path> -type f

Find only directories within a directory tree

$find <path> -type d

Find all files with a .txt extension

$find <path> -name "*.txt"

Find files matching a name pattern, case-insensitively

$find <path> -iname <pattern>

Find files larger than the specified size

$find <path> -size +<n>M

Find files smaller than the specified size

$find <path> -size -<n>M

Find files modified within the last <n> days

$find <path> -mtime -<n>

Find files modified more than <n> days ago

$find <path> -mtime +<n>

Find files newer than a reference file

$find <path> -newer <file>

Find empty files and directories

$find <path> -empty

Find files with specific permissions

$find <path> -perm <mode>

Find files owned by a specific user

$find <path> -user <username>

Find files belonging to a specific group

$find <path> -group <groupname>

Limit find depth to <n> levels of subdirectories

$find <path> -maxdepth <n>

Start find at least <n> levels deep

$find <path> -mindepth <n>

Execute a command on each file found

$find <path> -exec <command> {} \;

Execute a command on all found files at once

$find <path> -exec <command> {} +

Delete all files found matching the criteria

$find <path> -delete

Find files that do NOT match the specified name pattern

$find <path> -not -name <pattern>

Find files matching either of two name patterns

$find <path> \( -name <p1> -o -name <p2> \)

Search for a pattern in a file and print matching lines

$grep <pattern> <file>

Recursively search for a pattern in all files under a path

$grep -r <pattern> <path>

Search for a pattern case-insensitively

$grep -i <pattern> <file>

Print lines that do NOT match the pattern

$grep -v <pattern> <file>

Print matching lines along with their line numbers

$grep -n <pattern> <file>

Print only the names of files that contain matches

$grep -l <pattern> <path>

Count the number of matching lines in a file

$grep -c <pattern> <file>

Match only whole words, not partial matches

$grep -w <pattern> <file>

Match only whole lines that exactly match the pattern

$grep -x <pattern> <file>

Print <n> lines of context after each match

$grep -A <n> <pattern> <file>

Print <n> lines of context before each match

$grep -B <n> <pattern> <file>

Print <n> lines of context before and after each match

$grep -C <n> <pattern> <file>

Use extended regular expressions for matching

$grep -E <pattern> <file>

Use Perl-compatible regular expressions for matching

$grep -P <pattern> <file>

Print only the matched part of each line

$grep -o <pattern> <file>

Quietly check if a pattern matches, returning exit code only

$grep -q <pattern> <file>

Recursively search only files matching a filename pattern

$grep --include=<pattern> -r <search> <path>

Recursively search excluding files matching a filename pattern

$grep --exclude=<pattern> -r <search> <path>

Quickly find files by name using a prebuilt database

$locate <pattern>

Update the file database used by locate

$updatedb

Show the full path of an executable command

$which <command>

Find the binary, source, and manual page for a command

$whereis <command>

Show how a command name would be interpreted by the shell

$type <command>

Permissions & Ownership

Change the file permissions using numeric or symbolic mode

$chmod <mode> <file>

Set permissions to rwxr-xr-x (owner full, others read/execute)

$chmod 755 <file>

Set permissions to rw-r--r-- (owner read/write, others read)

$chmod 644 <file>

Set permissions to rw------- (owner read/write only)

$chmod 600 <file>

Add execute permission for all users

$chmod +x <file>

Remove execute permission for all users

$chmod -x <file>

Add execute permission for the file owner only

$chmod u+x <file>

Add write permission for the group

$chmod g+w <file>

Remove read permission for others

$chmod o-r <file>

Recursively change permissions for a directory and its contents

$chmod -R <mode> <directory>

Change the owner of a file

$chown <user> <file>

Change both the owner and group of a file

$chown <user>:<group> <file>

Recursively change owner and group for a directory

$chown -R <user>:<group> <directory>

Change the group ownership of a file

$chgrp <group> <file>

Recursively change group ownership of a directory

$chgrp -R <group> <directory>

Display the current default file creation permission mask

$umask

Set the default file creation permission mask

$umask <mode>

Display detailed metadata and status of a file

$stat <file>

Display the numeric permissions and name of a file

$stat -c "%a %n" <file>

Get the access control list for a file

$getfacl <file>

Set an access control list entry for a specific user

$setfacl -m u:<user>:<perms> <file>

Remove a user's access control list entry

$setfacl -x u:<user> <file>

Process Management

Show currently running processes for the current shell

$ps

Show all running processes with detailed information

$ps aux

Filter running processes by name

$ps aux | grep <process>

Show all processes in full-format listing

$ps -ef

Show information for a specific process ID

$ps -p <pid>

List processes sorted by CPU usage descending

$ps --sort=-%cpu

List processes sorted by memory usage descending

$ps --sort=-%mem

Display real-time view of running processes and system resources

$top

Show only processes belonging to a specific user in top

$top -u <user>

Monitor a specific process by PID in top

$top -p <pid>

Display an interactive process viewer with mouse support

$htop

Send the default SIGTERM signal to a process to terminate it

$kill <pid>

Send SIGKILL to forcefully terminate a process immediately

$kill -9 <pid>

List all available signal names

$kill -l

Terminate all processes with the specified name

$killall <name>

Forcefully terminate all processes with the specified name

$killall -9 <name>

Kill processes matching a name pattern

$pkill <pattern>

Kill all processes owned by a specific user

$pkill -u <user>

List PIDs of processes matching a name pattern

$pgrep <pattern>

List all background jobs in the current shell session

$jobs

Resume the most recently suspended job in the background

$bg

Resume a specific job number in the background

$bg %<n>

Bring the most recently backgrounded job to the foreground

$fg

Bring a specific job number to the foreground

$fg %<n>

Run a command in the background

$<command> &

Run a command immune to hangups, continuing after logout

$nohup <command> &

Wait for all background jobs to complete

$wait

Wait for a specific process ID to complete

$wait <pid>

Run a command with a modified scheduling priority

$nice -n <value> <command>

Change the priority of a currently running process

$renice <value> -p <pid>

Pause execution for a specified number of seconds

$sleep <seconds>

Run a command and kill it if it exceeds the timeout

$timeout <seconds> <command>

Repeatedly run a command every 2 seconds and display output

$watch <command>

Repeatedly run a command at a custom interval

$watch -n <seconds> <command>

System Information

Print all system information including kernel and architecture

$uname -a

Print the kernel release version

$uname -r

Print the operating system name

$uname -s

Print the machine hardware architecture

$uname -m

Print or set the system's hostname

$hostname

Print all IP addresses of the host

$hostname -I

Print the username of the currently logged-in user

$whoami

Print the UID, GID, and group memberships of the current user

$id

Print the UID, GID, and groups for a specific user

$id <user>

Show how long the system has been running and load averages

$uptime

Display the current date and time

$date

Display the current date in YYYY-MM-DD format

$date +"%Y-%m-%d"

Display a date parsed from a human-readable string

$date -d "<string>"

Display a calendar for the current month

$cal

Display a calendar for the entire specified year

$cal <year>

Report file system disk space usage

$df

Report disk space usage in human-readable format

$df -h

Report disk space usage including file system type

$df -T

Estimate file and directory space usage

$du

Show disk usage in human-readable format

$du -h

Show total disk usage of a directory in human-readable format

$du -sh <directory>

Show disk usage of all files and directories recursively

$du -ah <directory>

Show disk usage for immediate subdirectories only

$du --max-depth=1 -h

Display memory usage statistics

$free

Display memory usage in human-readable format

$free -h

Display memory usage in megabytes

$free -m

Display detailed CPU architecture information

$lscpu

List information about all available block storage devices

$lsblk

List all USB buses and devices connected

$lsusb

List all PCI buses and devices connected

$lspci

List detailed hardware configuration information

$lshw

Read hardware information from the DMI/SMBIOS table

$dmidecode

Print all environment variables for the current session

$env

Print the values of environment variables

$printenv

Print the value of a specific environment variable

$printenv <variable>

Print the value of a shell or environment variable

$echo $<variable>

Set and export an environment variable to child processes

$export <variable>=<value>

Remove an environment variable from the current session

$unset <variable>

Network

Send ICMP echo requests to test connectivity to a host

$ping <host>

Send exactly <n> ping packets to a host

$ping -c <n> <host>

Set the interval between ping packets

$ping -i <seconds> <host>

Set the packet size for ping

$ping -s <size> <host>

Transfer data from or to a URL

$curl <url>

Download a URL and save it to a specific file

$curl -o <file> <url>

Download a file keeping its original remote filename

$curl -O <url>

Follow HTTP redirects automatically

$curl -L <url>

Fetch only the HTTP response headers

$curl -I <url>

Send a POST request with data to a URL

$curl -X POST -d <data> <url>

Send a request with a custom HTTP header

$curl -H "<header>" <url>

Authenticate with a username and password

$curl -u <user>:<pass> <url>

Run curl without progress meter or error messages

$curl --silent <url>

Allow insecure connections, skipping SSL certificate verification

$curl -k <url>

Download a file from a URL

$wget <url>

Download a URL and save it to a specific filename

$wget -O <file> <url>

Download a URL quietly without output

$wget -q <url>

Recursively download a website

$wget -r <url>

Continue a previously interrupted download

$wget -c <url>

Download skipping SSL certificate verification

$wget --no-check-certificate <url>

Display or configure network interface parameters

$ifconfig

Show all network interface addresses

$ip addr

Show the address of a specific network interface

$ip addr show <interface>

Show or modify the state of network interfaces

$ip link

Show the kernel routing table

$ip route

List all listening TCP and UDP ports

$netstat -tuln

List all network connections with process IDs

$netstat -anp

List all listening sockets (modern replacement for netstat)

$ss -tuln

List all sockets with process information

$ss -anp

Trace the network path packets take to reach a host

$traceroute <host>

Query DNS to find the IP address of a domain

$nslookup <domain>

Perform a detailed DNS lookup for a domain

$dig <domain>

Perform a DNS lookup for a specific record type

$dig <domain> <type>

Look up a domain's IP address

$host <domain>

Connect to a remote host over SSH

$ssh <user>@<host>

Connect to a remote host on a specific SSH port

$ssh -p <port> <user>@<host>

Connect using a specific private key file

$ssh -i <keyfile> <user>@<host>

Generate a new 4096-bit RSA SSH key pair

$ssh-keygen -t rsa -b 4096

Copy your public key to a remote host for passwordless login

$ssh-copy-id <user>@<host>

Securely copy a file to a remote host

$scp <file> <user>@<host>:<path>

Securely copy a file from a remote host

$scp <user>@<host>:<path> <local>

Recursively copy a directory to a remote host

$scp -r <dir> <user>@<host>:<path>

Synchronize files with verbose archive mode

$rsync -av <source> <destination>

Synchronize files to a remote host with compression

$rsync -avz <source> <user>@<host>:<path>

Synchronize and delete files at destination not in source

$rsync --delete <source> <destination>

Dry run sync to preview what would be transferred

$rsync -n <source> <destination>

Text Processing

Print text or variable values to standard output

$echo <text>

Print text without a trailing newline

$echo -n <text>

Print text interpreting backslash escape sequences

$echo -e <text>

Format and print data according to a format string

$printf <format> <args>

Replace the first occurrence of a pattern in each line

$sed 's/<old>/<new>/' <file>

Replace all occurrences of a pattern in each line

$sed 's/<old>/<new>/g' <file>

Edit a file in-place replacing all occurrences of a pattern

$sed -i 's/<old>/<new>/g' <file>

Print only line number <n> of a file

$sed -n '<n>p' <file>

Print only lines from start to end of a file

$sed -n '<start>,<end>p' <file>

Delete lines matching a pattern

$sed '/<pattern>/d' <file>

Print only lines matching a pattern

$sed -n '/<pattern>/p' <file>

Print the first field of each line

$awk '{print $1}' <file>

Print the first field using a custom delimiter

$awk -F '<delim>' '{print $1}' <file>

Print a specific line number from a file

$awk 'NR==<n>' <file>

Print lines matching a pattern using awk

$awk '/pattern/ {print}' <file>

Sum the values of the first column in a file

$awk '{sum += $1} END {print sum}' <file>

Skip the first line (header) and print the rest

$awk 'NR > 1' <file>

Cut fields from each line of a file using a delimiter

$cut -d '<delim>' -f <fields> <file>

Cut specific character positions from each line

$cut -c <range> <file>

Cut a specific field from tab-delimited input

$cut -f <n> <file>

Sort the lines of a file alphabetically

$sort <file>

Sort lines in reverse order

$sort -r <file>

Sort lines numerically

$sort -n <file>

Sort by a specific field/column number

$sort -k <n> <file>

Sort and remove duplicate lines

$sort -u <file>

Sort by a specific field using a custom delimiter

$sort -t '<delim>' -k <n> <file>

Remove adjacent duplicate lines from a file

$uniq <file>

Count and print the number of occurrences of each unique line

$uniq -c <file>

Print only the duplicate lines

$uniq -d <file>

Print only unique, non-duplicated lines

$uniq -u <file>

Translate or replace characters from set1 with set2

$tr '<set1>' '<set2>'

Delete specified characters from input

$tr -d '<chars>'

Squeeze repeated characters into one

$tr -s '<chars>'

Convert lowercase letters to uppercase

$tr a-z A-Z

Read from stdin and write to both stdout and a file

$tee <file>

Append stdin to a file while also printing to stdout

$tee -a <file>

Build and execute commands from standard input

$xargs <command>

Pass at most <n> arguments per command invocation

$xargs -n <n> <command>

Replace {} with each input line when running a command

$xargs -I {} <command> {}

Run up to <n> commands in parallel

$xargs -P <n> <command>

Compare two files line by line

$diff <file1> <file2>

Compare two files showing unified diff format

$diff -u <file1> <file2>

Recursively compare two directories

$diff -r <dir1> <dir2>

Apply a patch file to an original file

$patch <file> < <patch>

Join lines of two files on a common field

$join <file1> <file2>

Merge lines of files side by side

$paste <file1> <file2>

Redirection & Pipelines

Redirect standard output to a file, overwriting it

$<command> > <file>

Redirect standard output and append to a file

$<command> >> <file>

Redirect a file as standard input to a command

$<command> < <file>

Redirect standard error output to a file

$<command> 2> <file>

Append standard error to a file

$<command> 2>> <file>

Redirect both stdout and stderr to a file

$<command> &> <file>

Redirect stderr to the same destination as stdout

$<command> 2>&1

Discard standard output

$<command> > /dev/null

Discard both standard output and standard error

$<command> > /dev/null 2>&1

Pipe the output of command1 as input to command2

$<command1> | <command2>

Chain multiple commands together with pipes

$<command1> | <command2> | <command3>

Run command2 only if command1 succeeds

$<command1> && <command2>

Run command2 only if command1 fails

$<command1> || <command2>

Run command1 then command2 regardless of exit status

$<command1> ; <command2>

Provide a here-document as standard input to a command

$command <<EOF ... EOF

Feed a here-string directly as stdin to a command

$<command> <<< "<string>"

Open a file on file descriptor <n> for reading

$exec <n>< <file>

Open a file on file descriptor <n> for writing

$exec <n>> <file>

Archiving & Compression

Create a tar archive from specified files or directories

$tar -cvf <archive>.tar <files>

Extract all files from a tar archive

$tar -xvf <archive>.tar

List the contents of a tar archive without extracting

$tar -tvf <archive>.tar

Create a gzip-compressed tar archive

$tar -cvzf <archive>.tar.gz <files>

Extract a gzip-compressed tar archive

$tar -xvzf <archive>.tar.gz

Create a bzip2-compressed tar archive

$tar -cvjf <archive>.tar.bz2 <files>

Extract a bzip2-compressed tar archive

$tar -xvjf <archive>.tar.bz2

Create an xz-compressed tar archive

$tar -cvJf <archive>.tar.xz <files>

Extract an xz-compressed tar archive

$tar -xvJf <archive>.tar.xz

Extract a tar archive into a specific directory

$tar -xvf <archive>.tar -C <directory>

Create a tar archive excluding files matching a pattern

$tar --exclude=<pattern> -cvzf <archive>.tar.gz <files>

Compress a file using gzip, replacing the original

$gzip <file>

Decompress a gzip-compressed file

$gzip -d <file>.gz

Compress a file with gzip while keeping the original

$gzip -k <file>

List the compression ratio of a gzip file

$gzip -l <file>.gz

Decompress a gzip file

$gunzip <file>.gz

Compress a file using bzip2

$bzip2 <file>

Decompress a bzip2-compressed file

$bzip2 -d <file>.bz2

Decompress a bzip2 file

$bunzip2 <file>.bz2

Compress a file using xz

$xz <file>

Decompress an xz-compressed file

$xz -d <file>.xz

Create a zip archive from specified files

$zip <archive>.zip <files>

Recursively zip an entire directory

$zip -r <archive>.zip <directory>

Extract all files from a zip archive

$unzip <archive>.zip

Extract a zip archive into a specific directory

$unzip <archive>.zip -d <directory>

List files in a zip archive without extracting

$unzip -l <archive>.zip

User Management

Show who is currently logged into the system

$who

Show logged-in users and their current activity

$w

Show a list of recent logins

$last

Show the most recent login for all users

$lastlog

Create a new user account

$useradd <username>

Create a new user and create their home directory

$useradd -m <username>

Create a user with a specific default shell

$useradd -s <shell> <username>

Create a user and set their primary group

$useradd -g <group> <username>

Create a user and add them to supplementary groups

$useradd -G <groups> <username>

Add an existing user to a supplementary group

$usermod -aG <group> <username>

Change the default shell of a user

$usermod -s <shell> <username>

Rename a user account

$usermod -l <new> <old>

Lock a user account

$usermod -L <username>

Unlock a user account

$usermod -U <username>

Delete a user account

$userdel <username>

Delete a user account and their home directory

$userdel -r <username>

Change the password for the current user

$passwd

Change the password for a specific user

$passwd <username>

Lock a user's password

$passwd -l <username>

Unlock a user's password

$passwd -u <username>

Create a new group

$groupadd <groupname>

Delete an existing group

$groupdel <groupname>

Show which groups a user belongs to

$groups <username>

Switch to another user account

$su <username>

Switch to root with a full login environment

$su -

Execute a command with superuser privileges

$sudo <command>

Execute a command as a specific user via sudo

$sudo -u <user> <command>

Open an interactive root shell via sudo

$sudo -i

Re-run the previous command with sudo

$sudo !!

Safely edit the sudoers file

$visudo

Shell Scripting

Shebang line to specify bash as the script interpreter

$#!/bin/bash

Execute a shell script using bash

$bash <script>.sh

Make a script executable and then run it

$chmod +x <script>.sh && ./<script>.sh

Execute a script in the current shell environment

$source <script>.sh

Dot-source a script, executing it in the current shell

$. <script>.sh

Exit the script immediately if any command fails

$set -e

Exit the script if any undefined variable is used

$set -u

Print each command before executing it for debugging

$set -x

Return the exit status of the last failed command in a pipeline

$set -o pipefail

Enable strict mode: exit on error, undefined vars, and pipefail

$set -euxo pipefail

Assign a value to a shell variable (no spaces around =)

$<variable>=<value>

Declare a read-only variable that cannot be changed

$readonly <variable>=<value>

Declare a variable local to a function

$local <variable>=<value>

Declare a variable as an integer type

$declare -i <variable>

Declare an indexed array variable

$declare -a <array>

Declare an associative array (dictionary) variable

$declare -A <array>

Basic if-then-fi conditional block

$if [ <condition> ]; then ... fi

If-else conditional block

$if [ <condition> ]; then ... else ... fi

If block using bash extended test syntax

$if [[ <condition> ]]; then ... fi

Loop over a list of items

$for <var> in <list>; do ... done

C-style arithmetic for loop

$for (( i=0; i<n; i++ )); do ... done

Execute a block while a condition is true

$while [ <condition> ]; do ... done

Read and process a file line by line

$while read line; do ... done < <file>

Execute a block until a condition becomes true

$until [ <condition> ]; do ... done

Match a variable against multiple patterns

$case <var> in <pattern>) ... ;; esac

Define a reusable function

$function <name>() { ... }

Define a function without the function keyword

$<name>() { ... }

Exit a function with a specific return code

$return <code>

Exit the script with a specific exit code

$exit <code>

Get the exit status of the last executed command

$$?

Get the name of the current script

$$0

Access positional arguments passed to the script

$$1, $2 ...

Access all positional arguments as separate quoted strings

$$@

Access all positional arguments as a single string

$$*

Get the count of positional arguments

$$#

Get the PID of the most recently backgrounded process

$$!

Get the PID of the current shell process

$$$

Capture the output of a command into a variable

$$(<command>)

Command substitution using backticks (older syntax)

$`<command>`

Perform arithmetic expression evaluation

$$(( <expression> ))

Execute a command when a specific signal is received

$trap '<command>' <signal>

Execute a cleanup command when the script exits

$trap '<command>' EXIT

Parse command-line options in a script

$getopts <optstring> <variable>

Shift positional arguments left by one

$shift

Shift positional arguments left by <n>

$shift <n>

Read a line from stdin into a variable

$read <variable>

Prompt the user and read their input

$read -p "<prompt>" <variable>

Read input silently without echoing characters

$read -s <variable>

Read input into an indexed array

$read -a <array>

Check if a file exists and is a regular file

$test -f <file>

Check if a path exists and is a directory

$test -d <directory>

Check if a string is empty

$test -z <string>

Check if a string is non-empty

$test -n <string>

Test if two integers are equal

$[ <expr1> -eq <expr2> ]

Test if two integers are not equal

$[ <expr1> -ne <expr2> ]

Test if the first integer is less than the second

$[ <expr1> -lt <expr2> ]

Test if the first integer is greater than the second

$[ <expr1> -gt <expr2> ]

Package Management

Update the list of available packages and their versions

$apt update

Install the newest versions of all installed packages

$apt upgrade

Install a specific package

$apt install <package>

Install a package automatically answering yes to prompts

$apt install -y <package>

Remove a package but keep its configuration files

$apt remove <package>

Remove a package and all its configuration files

$apt purge <package>

Remove packages that were automatically installed and no longer needed

$apt autoremove

Search for a package in the repository

$apt search <query>

Show detailed information about a specific package

$apt show <package>

List all installed packages

$apt list --installed

Show the installed and candidate version of a package

$apt-cache policy <package>

Install a .deb package file

$dpkg -i <package>.deb

Remove an installed package

$dpkg -r <package>

List all installed packages

$dpkg -l

List all files installed by a package

$dpkg -L <package>

Show the status and info of an installed package

$dpkg -s <package>

Install a package on RPM-based systems

$yum install <package>

Update all packages on RPM-based systems

$yum update

Remove a package from RPM-based systems

$yum remove <package>

Search for a package on RPM-based systems

$yum search <query>

Install a package using the modern DNF package manager

$dnf install <package>

Update all packages using DNF

$dnf update

Remove a package using DNF

$dnf remove <package>

Install a snap package

$snap install <package>

Remove a snap package

$snap remove <package>

List all installed snap packages

$snap list

Install a Flatpak application

$flatpak install <package>

Remove a Flatpak application

$flatpak remove <package>

Disk & Storage

Mount a filesystem device to a directory

$mount <device> <mountpoint>

Unmount a mounted filesystem

$umount <mountpoint>

Check if a device is currently mounted

$mount | grep <device>

List all disk partitions

$fdisk -l

Open an interactive partition editor for a disk

$fdisk <device>

Open the parted partition editor for a disk

$parted <device>

Format a device with the ext4 filesystem

$mkfs.ext4 <device>

Format a device with the FAT filesystem

$mkfs.vfat <device>

Set up a swap space on a device

$mkswap <device>

Enable a swap space

$swapon <device>

Disable a swap space

$swapoff <device>

Copy and convert data from input to output block by block

$dd if=<input> of=<output> bs=<size>

Create a 100MB file filled with zeros

$dd if=/dev/zero of=<file> bs=1M count=100

Write an ISO image to a device

$dd if=<image>.iso of=<device>

Check and repair a filesystem

$fsck <device>

Force a check of an ext2/3/4 filesystem

$e2fsck -f <device>

Resize an ext2/3/4 filesystem

$resize2fs <device>

Scheduling & Automation

Edit the current user's crontab file

$crontab -e

List the current user's cron jobs

$crontab -l

Remove the current user's crontab file

$crontab -r

Edit the crontab for a specific user

$crontab -u <user> -e

Schedule a command to run once at a specific time

$at <time>

List all pending at jobs

$atq

Remove a pending at job by its job number

$atrm <job>

Start a systemd service

$systemctl start <service>

Stop a running systemd service

$systemctl stop <service>

Restart a systemd service

$systemctl restart <service>

Check the status of a systemd service

$systemctl status <service>

Enable a service to start automatically at boot

$systemctl enable <service>

Disable a service from starting at boot

$systemctl disable <service>

List all active systemd services

$systemctl list-units --type=service

View the logs for a specific systemd service

$journalctl -u <service>

Follow the system journal in real-time

$journalctl -f

Show journal entries since a specific date

$journalctl --since "<date>"

Miscellaneous

Show the command history for the current session

$history

Clear all command history

$history -c

Search through command history for a specific command

$history | grep <command>

Re-run command number <n> from history

$!<n>

Re-run the most recently executed command

$!!

Re-run the most recent command starting with a string

$!<string>

Create a shortcut alias for a command

$alias <name>='<command>'

List all currently defined aliases

$alias

Remove a defined alias

$unalias <name>

Display the manual page for a command

$man <command>

Search manual page descriptions for a keyword

$man -k <keyword>

Display the info manual for a command

$info <command>

Display help information for most commands when appended

$--help

Clear the terminal screen

$clear

Reset the terminal to its initial state

$reset

Exit the current shell session

$exit

Log out of a login shell

$logout

Record a terminal session to a file

$script <file>

Start a new tmux terminal multiplexer session

$tmux

Start a new named tmux session

$tmux new -s <name>

Attach to an existing tmux session

$tmux attach -t <name>

List all active tmux sessions

$tmux ls

Start a new GNU screen session

$screen

Resume a detached screen session

$screen -r

Open a file with the default associated application

$xdg-open <file>

Copy file contents to the system clipboard

$xclip -sel clip < <file>

Open an interactive arbitrary precision calculator

$bc

Open bc with math library for floating point operations

$bc -l

Print the prime factorization of a number

$factor <number>

Generate a sequence of numbers from start to end

$seq <start> <end>

Generate a sequence of numbers using a custom separator

$seq -s '<sep>' <start> <end>

Repeatedly output 'y' to auto-accept prompts

$yes

Repeatedly output a custom string

$yes <string>