Bash commands

Unix shell and command language

539 commands

Navigation & File System

  • pwd

    Print the full path of the current working directory

  • ls

    List files and directories in the current directory

  • ls -l

    List files in long format with permissions, size, and date

  • ls -a

    List all files including hidden files starting with a dot

  • ls -la

    List all files including hidden ones in long format

  • ls -lh

    List files in long format with human-readable file sizes

  • ls -lt

    List files sorted by modification time, newest first

  • ls -lS

    List files sorted by size, largest first

  • ls -R

    Recursively list all files in subdirectories

  • ls -d */

    List only directories in the current directory

  • ls --color=auto

    List files with colorized output for file types

  • cd <directory>

    Change the current working directory to the specified path

  • cd ..

    Move up one level to the parent directory

  • cd ~

    Navigate to the current user's home directory

  • cd -

    Switch back to the previously visited directory

  • cd /

    Navigate to the root directory of the filesystem

  • cd ~/Documents

    Navigate to the Documents folder in the home directory

  • pushd <directory>

    Save current directory and switch to the specified directory

  • popd

    Return to the directory saved by the last pushd command

  • dirs

    Display the list of currently remembered directories

  • tree

    Display directory structure in a visual tree format

  • tree -L <n>

    Display directory tree limited to <n> levels deep

  • tree -a

    Display all files including hidden ones in tree format

  • tree -d

    Display only directories in tree format

File & Directory Operations

  • mkdir <directory>

    Create a new directory with the specified name

  • mkdir -p <path>

    Create nested directories, creating parent directories as needed

  • mkdir -m <mode> <directory>

    Create a directory with specific permissions

  • rmdir <directory>

    Remove an empty directory

  • rmdir -p <path>

    Remove a directory and its empty parent directories

  • rm <file>

    Delete a file permanently

  • rm -r <directory>

    Recursively delete a directory and all its contents

  • rm -f <file>

    Forcefully delete a file without prompting

  • rm -rf <directory>

    Forcefully and recursively delete a directory without prompting

  • rm -i <file>

    Delete a file but prompt for confirmation first

  • rm -v <file>

    Delete a file and print each action verbosely

  • cp <source> <destination>

    Copy a file from source to destination

  • cp -r <source> <destination>

    Recursively copy a directory and its contents

  • cp -p <source> <destination>

    Copy a file preserving its permissions, timestamps, and ownership

  • cp -i <source> <destination>

    Copy a file but prompt before overwriting existing files

  • cp -v <source> <destination>

    Copy a file and print each action verbosely

  • cp -u <source> <destination>

    Copy a file only if source is newer than destination

  • cp -a <source> <destination>

    Archive copy, preserving all attributes and structure recursively

  • mv <source> <destination>

    Move or rename a file or directory

  • mv -i <source> <destination>

    Move a file but prompt before overwriting existing files

  • mv -f <source> <destination>

    Forcefully move a file without prompting

  • mv -v <source> <destination>

    Move a file and print each action verbosely

  • mv -n <source> <destination>

    Move a file but do not overwrite any existing destination

  • touch <file>

    Create an empty file or update its timestamps

  • touch -t <timestamp> <file>

    Set a specific timestamp on a file

  • touch -a <file>

    Update only the access time of a file

  • touch -m <file>

    Update only the modification time of a file

  • ln <source> <link>

    Create a hard link to a file

  • ln -s <source> <link>

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

  • ln -sf <source> <link>

    Forcefully create a symbolic link, overwriting existing links

  • readlink <link>

    Print the target path a symbolic link points to

  • readlink -f <link>

    Print the canonicalized absolute path of a symbolic link

File Viewing & Editing

  • cat <file>

    Print the contents of a file to standard output

  • cat -n <file>

    Print file contents with line numbers

  • cat -A <file>

    Print file contents showing non-printing characters

  • cat <file1> <file2>

    Concatenate and print multiple files

  • cat > <file>

    Create a new file and write from standard input

  • cat >> <file>

    Append standard input to the end of a file

  • less <file>

    View file contents with scrollable pagination

  • less -N <file>

    View file contents with line numbers in less

  • less +F <file>

    Open a file and follow it for real-time updates

  • more <file>

    View file contents one screen at a time

  • head <file>

    Print the first 10 lines of a file

  • head -n <n> <file>

    Print the first <n> lines of a file

  • head -c <n> <file>

    Print the first <n> bytes of a file

  • tail <file>

    Print the last 10 lines of a file

  • tail -n <n> <file>

    Print the last <n> lines of a file

  • tail -f <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 -c <n> <file>

    Print the last <n> bytes of a file

  • nano <file>

    Open a file in the nano terminal text editor

  • vim <file>

    Open a file in the vim terminal text editor

  • vi <file>

    Open a file in the vi terminal text editor

  • gedit <file>

    Open a file in the GNOME graphical text editor

  • wc <file>

    Count lines, words, and bytes in a file

  • wc -l <file>

    Count only the number of lines in a file

  • wc -w <file>

    Count only the number of words in a file

  • wc -c <file>

    Count only the number of bytes in a file

  • wc -m <file>

    Count the number of characters in a file

Search & Find

  • find <path> -name <pattern>

    Find files matching a name pattern in a directory tree

  • find <path> -type f

    Find only regular files within a directory tree

  • find <path> -type d

    Find only directories within a directory tree

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

    Find all files with a .txt extension

  • find <path> -iname <pattern>

    Find files matching a name pattern, case-insensitively

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

    Find files larger than the specified size

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

    Find files smaller than the specified size

  • find <path> -mtime -<n>

    Find files modified within the last <n> days

  • find <path> -mtime +<n>

    Find files modified more than <n> days ago

  • find <path> -newer <file>

    Find files newer than a reference file

  • find <path> -empty

    Find empty files and directories

  • find <path> -perm <mode>

    Find files with specific permissions

  • find <path> -user <username>

    Find files owned by a specific user

  • find <path> -group <groupname>

    Find files belonging to a specific group

  • find <path> -maxdepth <n>

    Limit find depth to <n> levels of subdirectories

  • find <path> -mindepth <n>

    Start find at least <n> levels deep

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

    Execute a command on each file found

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

    Execute a command on all found files at once

  • find <path> -delete

    Delete all files found matching the criteria

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

    Find files that do NOT match the specified name pattern

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

    Find files matching either of two name patterns

  • grep <pattern> <file>

    Search for a pattern in a file and print matching lines

  • grep -r <pattern> <path>

    Recursively search for a pattern in all files under a path

  • grep -i <pattern> <file>

    Search for a pattern case-insensitively

  • grep -v <pattern> <file>

    Print lines that do NOT match the pattern

  • grep -n <pattern> <file>

    Print matching lines along with their line numbers

  • grep -l <pattern> <path>

    Print only the names of files that contain matches

  • grep -c <pattern> <file>

    Count the number of matching lines in a file

  • grep -w <pattern> <file>

    Match only whole words, not partial matches

  • grep -x <pattern> <file>

    Match only whole lines that exactly match the pattern

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

    Print <n> lines of context after each match

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

    Print <n> lines of context before each match

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

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

  • grep -E <pattern> <file>

    Use extended regular expressions for matching

  • grep -P <pattern> <file>

    Use Perl-compatible regular expressions for matching

  • grep -o <pattern> <file>

    Print only the matched part of each line

  • grep -q <pattern> <file>

    Quietly check if a pattern matches, returning exit code only

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

    Recursively search only files matching a filename pattern

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

    Recursively search excluding files matching a filename pattern

  • locate <pattern>

    Quickly find files by name using a prebuilt database

  • updatedb

    Update the file database used by locate

  • which <command>

    Show the full path of an executable command

  • whereis <command>

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

  • type <command>

    Show how a command name would be interpreted by the shell

Permissions & Ownership

  • chmod <mode> <file>

    Change the file permissions using numeric or symbolic mode

  • chmod 755 <file>

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

  • chmod 644 <file>

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

  • chmod 600 <file>

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

  • chmod +x <file>

    Add execute permission for all users

  • chmod -x <file>

    Remove execute permission for all users

  • chmod u+x <file>

    Add execute permission for the file owner only

  • chmod g+w <file>

    Add write permission for the group

  • chmod o-r <file>

    Remove read permission for others

  • chmod -R <mode> <directory>

    Recursively change permissions for a directory and its contents

  • chown <user> <file>

    Change the owner of a file

  • chown <user>:<group> <file>

    Change both the owner and group of a file

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

    Recursively change owner and group for a directory

  • chgrp <group> <file>

    Change the group ownership of a file

  • chgrp -R <group> <directory>

    Recursively change group ownership of a directory

  • umask

    Display the current default file creation permission mask

  • umask <mode>

    Set the default file creation permission mask

  • stat <file>

    Display detailed metadata and status of a file

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

    Display the numeric permissions and name of a file

  • getfacl <file>

    Get the access control list for a file

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

    Set an access control list entry for a specific user

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

    Remove a user's access control list entry

Process Management

  • ps

    Show currently running processes for the current shell

  • ps aux

    Show all running processes with detailed information

  • ps aux | grep <process>

    Filter running processes by name

  • ps -ef

    Show all processes in full-format listing

  • ps -p <pid>

    Show information for a specific process ID

  • ps --sort=-%cpu

    List processes sorted by CPU usage descending

  • ps --sort=-%mem

    List processes sorted by memory usage descending

  • top

    Display real-time view of running processes and system resources

  • top -u <user>

    Show only processes belonging to a specific user in top

  • top -p <pid>

    Monitor a specific process by PID in top

  • htop

    Display an interactive process viewer with mouse support

  • kill <pid>

    Send the default SIGTERM signal to a process to terminate it

  • kill -9 <pid>

    Send SIGKILL to forcefully terminate a process immediately

  • kill -l

    List all available signal names

  • killall <name>

    Terminate all processes with the specified name

  • killall -9 <name>

    Forcefully terminate all processes with the specified name

  • pkill <pattern>

    Kill processes matching a name pattern

  • pkill -u <user>

    Kill all processes owned by a specific user

  • pgrep <pattern>

    List PIDs of processes matching a name pattern

  • jobs

    List all background jobs in the current shell session

  • bg

    Resume the most recently suspended job in the background

  • bg %<n>

    Resume a specific job number in the background

  • fg

    Bring the most recently backgrounded job to the foreground

  • fg %<n>

    Bring a specific job number to the foreground

  • <command> &

    Run a command in the background

  • nohup <command> &

    Run a command immune to hangups, continuing after logout

  • wait

    Wait for all background jobs to complete

  • wait <pid>

    Wait for a specific process ID to complete

  • nice -n <value> <command>

    Run a command with a modified scheduling priority

  • renice <value> -p <pid>

    Change the priority of a currently running process

  • sleep <seconds>

    Pause execution for a specified number of seconds

  • timeout <seconds> <command>

    Run a command and kill it if it exceeds the timeout

  • watch <command>

    Repeatedly run a command every 2 seconds and display output

  • watch -n <seconds> <command>

    Repeatedly run a command at a custom interval

System Information

  • uname -a

    Print all system information including kernel and architecture

  • uname -r

    Print the kernel release version

  • uname -s

    Print the operating system name

  • uname -m

    Print the machine hardware architecture

  • hostname

    Print or set the system's hostname

  • hostname -I

    Print all IP addresses of the host

  • whoami

    Print the username of the currently logged-in user

  • id

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

  • id <user>

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

  • uptime

    Show how long the system has been running and load averages

  • date

    Display the current date and time

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

    Display the current date in YYYY-MM-DD format

  • date -d "<string>"

    Display a date parsed from a human-readable string

  • cal

    Display a calendar for the current month

  • cal <year>

    Display a calendar for the entire specified year

  • df

    Report file system disk space usage

  • df -h

    Report disk space usage in human-readable format

  • df -T

    Report disk space usage including file system type

  • du

    Estimate file and directory space usage

  • du -h

    Show disk usage in human-readable format

  • du -sh <directory>

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

  • du -ah <directory>

    Show disk usage of all files and directories recursively

  • du --max-depth=1 -h

    Show disk usage for immediate subdirectories only

  • free

    Display memory usage statistics

  • free -h

    Display memory usage in human-readable format

  • free -m

    Display memory usage in megabytes

  • lscpu

    Display detailed CPU architecture information

  • lsblk

    List information about all available block storage devices

  • lsusb

    List all USB buses and devices connected

  • lspci

    List all PCI buses and devices connected

  • lshw

    List detailed hardware configuration information

  • dmidecode

    Read hardware information from the DMI/SMBIOS table

  • env

    Print all environment variables for the current session

  • printenv

    Print the values of environment variables

  • printenv <variable>

    Print the value of a specific environment variable

  • echo $<variable>

    Print the value of a shell or environment variable

  • export <variable>=<value>

    Set and export an environment variable to child processes

  • unset <variable>

    Remove an environment variable from the current session

Network

  • ping <host>

    Send ICMP echo requests to test connectivity to a host

  • ping -c <n> <host>

    Send exactly <n> ping packets to a host

  • ping -i <seconds> <host>

    Set the interval between ping packets

  • ping -s <size> <host>

    Set the packet size for ping

  • curl <url>

    Transfer data from or to a URL

  • curl -o <file> <url>

    Download a URL and save it to a specific file

  • curl -O <url>

    Download a file keeping its original remote filename

  • curl -L <url>

    Follow HTTP redirects automatically

  • curl -I <url>

    Fetch only the HTTP response headers

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

    Send a POST request with data to a URL

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

    Send a request with a custom HTTP header

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

    Authenticate with a username and password

  • curl --silent <url>

    Run curl without progress meter or error messages

  • curl -k <url>

    Allow insecure connections, skipping SSL certificate verification

  • wget <url>

    Download a file from a URL

  • wget -O <file> <url>

    Download a URL and save it to a specific filename

  • wget -q <url>

    Download a URL quietly without output

  • wget -r <url>

    Recursively download a website

  • wget -c <url>

    Continue a previously interrupted download

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

    Download skipping SSL certificate verification

  • ifconfig

    Display or configure network interface parameters

  • ip addr

    Show all network interface addresses

  • ip addr show <interface>

    Show the address of a specific network interface

  • ip link

    Show or modify the state of network interfaces

  • ip route

    Show the kernel routing table

  • netstat -tuln

    List all listening TCP and UDP ports

  • netstat -anp

    List all network connections with process IDs

  • ss -tuln

    List all listening sockets (modern replacement for netstat)

  • ss -anp

    List all sockets with process information

  • traceroute <host>

    Trace the network path packets take to reach a host

  • nslookup <domain>

    Query DNS to find the IP address of a domain

  • dig <domain>

    Perform a detailed DNS lookup for a domain

  • dig <domain> <type>

    Perform a DNS lookup for a specific record type

  • host <domain>

    Look up a domain's IP address

  • ssh <user>@<host>

    Connect to a remote host over SSH

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

    Connect to a remote host on a specific SSH port

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

    Connect using a specific private key file

  • ssh-keygen -t rsa -b 4096

    Generate a new 4096-bit RSA SSH key pair

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

    Copy your public key to a remote host for passwordless login

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

    Securely copy a file to a remote host

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

    Securely copy a file from a remote host

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

    Recursively copy a directory to a remote host

  • rsync -av <source> <destination>

    Synchronize files with verbose archive mode

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

    Synchronize files to a remote host with compression

  • rsync --delete <source> <destination>

    Synchronize and delete files at destination not in source

  • rsync -n <source> <destination>

    Dry run sync to preview what would be transferred

Text Processing

  • echo <text>

    Print text or variable values to standard output

  • echo -n <text>

    Print text without a trailing newline

  • echo -e <text>

    Print text interpreting backslash escape sequences

  • printf <format> <args>

    Format and print data according to a format string

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

    Replace the first occurrence of a pattern in each line

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

    Replace all occurrences of a pattern in each line

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

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

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

    Print only line number <n> of a file

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

    Print only lines from start to end of a file

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

    Delete lines matching a pattern

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

    Print only lines matching a pattern

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

    Print the first field of each line

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

    Print the first field using a custom delimiter

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

    Print a specific line number from a file

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

    Print lines matching a pattern using awk

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

    Sum the values of the first column in a file

  • awk 'NR > 1' <file>

    Skip the first line (header) and print the rest

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

    Cut fields from each line of a file using a delimiter

  • cut -c <range> <file>

    Cut specific character positions from each line

  • cut -f <n> <file>

    Cut a specific field from tab-delimited input

  • sort <file>

    Sort the lines of a file alphabetically

  • sort -r <file>

    Sort lines in reverse order

  • sort -n <file>

    Sort lines numerically

  • sort -k <n> <file>

    Sort by a specific field/column number

  • sort -u <file>

    Sort and remove duplicate lines

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

    Sort by a specific field using a custom delimiter

  • uniq <file>

    Remove adjacent duplicate lines from a file

  • uniq -c <file>

    Count and print the number of occurrences of each unique line

  • uniq -d <file>

    Print only the duplicate lines

  • uniq -u <file>

    Print only unique, non-duplicated lines

  • tr '<set1>' '<set2>'

    Translate or replace characters from set1 with set2

  • tr -d '<chars>'

    Delete specified characters from input

  • tr -s '<chars>'

    Squeeze repeated characters into one

  • tr a-z A-Z

    Convert lowercase letters to uppercase

  • tee <file>

    Read from stdin and write to both stdout and a file

  • tee -a <file>

    Append stdin to a file while also printing to stdout

  • xargs <command>

    Build and execute commands from standard input

  • xargs -n <n> <command>

    Pass at most <n> arguments per command invocation

  • xargs -I {} <command> {}

    Replace {} with each input line when running a command

  • xargs -P <n> <command>

    Run up to <n> commands in parallel

  • diff <file1> <file2>

    Compare two files line by line

  • diff -u <file1> <file2>

    Compare two files showing unified diff format

  • diff -r <dir1> <dir2>

    Recursively compare two directories

  • patch <file> < <patch>

    Apply a patch file to an original file

  • join <file1> <file2>

    Join lines of two files on a common field

  • paste <file1> <file2>

    Merge lines of files side by side

Redirection & Pipelines

  • <command> > <file>

    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> 2> <file>

    Redirect standard error output to a file

  • <command> 2>> <file>

    Append standard error to a file

  • <command> &> <file>

    Redirect both stdout and stderr to a file

  • <command> 2>&1

    Redirect stderr to the same destination as stdout

  • <command> > /dev/null

    Discard standard output

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

    Discard both standard output and standard error

  • <command1> | <command2>

    Pipe the output of command1 as input to command2

  • <command1> | <command2> | <command3>

    Chain multiple commands together with pipes

  • <command1> && <command2>

    Run command2 only if command1 succeeds

  • <command1> || <command2>

    Run command2 only if command1 fails

  • <command1> ; <command2>

    Run command1 then command2 regardless of exit status

  • command <<EOF ... EOF

    Provide a here-document as standard input to a command

  • <command> <<< "<string>"

    Feed a here-string directly as stdin to a command

  • exec <n>< <file>

    Open a file on file descriptor <n> for reading

  • exec <n>> <file>

    Open a file on file descriptor <n> for writing

Archiving & Compression

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

    Create a tar archive from specified files or directories

  • tar -xvf <archive>.tar

    Extract all files from a tar archive

  • tar -tvf <archive>.tar

    List the contents of a tar archive without extracting

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

    Create a gzip-compressed tar archive

  • tar -xvzf <archive>.tar.gz

    Extract a gzip-compressed tar archive

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

    Create a bzip2-compressed tar archive

  • tar -xvjf <archive>.tar.bz2

    Extract a bzip2-compressed tar archive

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

    Create an xz-compressed tar archive

  • tar -xvJf <archive>.tar.xz

    Extract an xz-compressed tar archive

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

    Extract a tar archive into a specific directory

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

    Create a tar archive excluding files matching a pattern

  • gzip <file>

    Compress a file using gzip, replacing the original

  • gzip -d <file>.gz

    Decompress a gzip-compressed file

  • gzip -k <file>

    Compress a file with gzip while keeping the original

  • gzip -l <file>.gz

    List the compression ratio of a gzip file

  • gunzip <file>.gz

    Decompress a gzip file

  • bzip2 <file>

    Compress a file using bzip2

  • bzip2 -d <file>.bz2

    Decompress a bzip2-compressed file

  • bunzip2 <file>.bz2

    Decompress a bzip2 file

  • xz <file>

    Compress a file using xz

  • xz -d <file>.xz

    Decompress an xz-compressed file

  • zip <archive>.zip <files>

    Create a zip archive from specified files

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

    Recursively zip an entire directory

  • unzip <archive>.zip

    Extract all files from a zip archive

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

    Extract a zip archive into a specific directory

  • unzip -l <archive>.zip

    List files in a zip archive without extracting

User Management

  • who

    Show who is currently logged into the system

  • w

    Show logged-in users and their current activity

  • last

    Show a list of recent logins

  • lastlog

    Show the most recent login for all users

  • useradd <username>

    Create a new user account

  • useradd -m <username>

    Create a new user and create their home directory

  • useradd -s <shell> <username>

    Create a user with a specific default shell

  • useradd -g <group> <username>

    Create a user and set their primary group

  • useradd -G <groups> <username>

    Create a user and add them to supplementary groups

  • usermod -aG <group> <username>

    Add an existing user to a supplementary group

  • usermod -s <shell> <username>

    Change the default shell of a user

  • usermod -l <new> <old>

    Rename a user account

  • usermod -L <username>

    Lock a user account

  • usermod -U <username>

    Unlock a user account

  • userdel <username>

    Delete a user account

  • userdel -r <username>

    Delete a user account and their home directory

  • passwd

    Change the password for the current user

  • passwd <username>

    Change the password for a specific user

  • passwd -l <username>

    Lock a user's password

  • passwd -u <username>

    Unlock a user's password

  • groupadd <groupname>

    Create a new group

  • groupdel <groupname>

    Delete an existing group

  • groups <username>

    Show which groups a user belongs to

  • su <username>

    Switch to another user account

  • su -

    Switch to root with a full login environment

  • sudo <command>

    Execute a command with superuser privileges

  • sudo -u <user> <command>

    Execute a command as a specific user via sudo

  • sudo -i

    Open an interactive root shell via sudo

  • sudo !!

    Re-run the previous command with sudo

  • visudo

    Safely edit the sudoers file

Shell Scripting

  • #!/bin/bash

    Shebang line to specify bash as the script interpreter

  • bash <script>.sh

    Execute a shell script using bash

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

    Make a script executable and then run it

  • source <script>.sh

    Execute a script in the current shell environment

  • . <script>.sh

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

  • set -e

    Exit the script immediately if any command fails

  • set -u

    Exit the script if any undefined variable is used

  • set -x

    Print each command before executing it for debugging

  • set -o pipefail

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

  • set -euxo pipefail

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

  • <variable>=<value>

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

  • readonly <variable>=<value>

    Declare a read-only variable that cannot be changed

  • local <variable>=<value>

    Declare a variable local to a function

  • declare -i <variable>

    Declare a variable as an integer type

  • declare -a <array>

    Declare an indexed array variable

  • declare -A <array>

    Declare an associative array (dictionary) variable

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

    Basic if-then-fi conditional block

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

    If-else conditional block

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

    If block using bash extended test syntax

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

    Loop over a list of items

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

    C-style arithmetic for loop

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

    Execute a block while a condition is true

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

    Read and process a file line by line

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

    Execute a block until a condition becomes true

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

    Match a variable against multiple patterns

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

    Define a reusable function

  • <name>() { ... }

    Define a function without the function keyword

  • return <code>

    Exit a function with a specific return code

  • exit <code>

    Exit the script with a specific exit code

  • $?

    Get the exit status of the last executed command

  • $0

    Get the name of the current script

  • $1, $2 ...

    Access positional arguments passed to the script

  • $@

    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

  • $(<command>)

    Capture the output of a command into a variable

  • `<command>`

    Command substitution using backticks (older syntax)

  • $(( <expression> ))

    Perform arithmetic expression evaluation

  • trap '<command>' <signal>

    Execute a command when a specific signal is received

  • trap '<command>' EXIT

    Execute a cleanup command when the script exits

  • getopts <optstring> <variable>

    Parse command-line options in a script

  • shift

    Shift positional arguments left by one

  • shift <n>

    Shift positional arguments left by <n>

  • read <variable>

    Read a line from stdin into a variable

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

    Prompt the user and read their input

  • read -s <variable>

    Read input silently without echoing characters

  • read -a <array>

    Read input into an indexed array

  • test -f <file>

    Check if a file exists and is a regular file

  • test -d <directory>

    Check if a path exists and is a directory

  • test -z <string>

    Check if a string is empty

  • test -n <string>

    Check if a string is non-empty

  • [ <expr1> -eq <expr2> ]

    Test if two integers are equal

  • [ <expr1> -ne <expr2> ]

    Test if two integers are not equal

  • [ <expr1> -lt <expr2> ]

    Test if the first integer is less than the second

  • [ <expr1> -gt <expr2> ]

    Test if the first integer is greater than the second

Package Management

  • apt update

    Update the list of available packages and their versions

  • apt upgrade

    Install the newest versions of all installed packages

  • apt install <package>

    Install a specific package

  • apt install -y <package>

    Install a package automatically answering yes to prompts

  • apt remove <package>

    Remove a package but keep its configuration files

  • apt purge <package>

    Remove a package and all its configuration files

  • apt autoremove

    Remove packages that were automatically installed and no longer needed

  • apt search <query>

    Search for a package in the repository

  • apt show <package>

    Show detailed information about a specific package

  • apt list --installed

    List all installed packages

  • apt-cache policy <package>

    Show the installed and candidate version of a package

  • dpkg -i <package>.deb

    Install a .deb package file

  • dpkg -r <package>

    Remove an installed package

  • dpkg -l

    List all installed packages

  • dpkg -L <package>

    List all files installed by a package

  • dpkg -s <package>

    Show the status and info of an installed package

  • yum install <package>

    Install a package on RPM-based systems

  • yum update

    Update all packages on RPM-based systems

  • yum remove <package>

    Remove a package from RPM-based systems

  • yum search <query>

    Search for a package on RPM-based systems

  • dnf install <package>

    Install a package using the modern DNF package manager

  • dnf update

    Update all packages using DNF

  • dnf remove <package>

    Remove a package using DNF

  • snap install <package>

    Install a snap package

  • snap remove <package>

    Remove a snap package

  • snap list

    List all installed snap packages

  • flatpak install <package>

    Install a Flatpak application

  • flatpak remove <package>

    Remove a Flatpak application

Disk & Storage

  • mount <device> <mountpoint>

    Mount a filesystem device to a directory

  • umount <mountpoint>

    Unmount a mounted filesystem

  • mount | grep <device>

    Check if a device is currently mounted

  • fdisk -l

    List all disk partitions

  • fdisk <device>

    Open an interactive partition editor for a disk

  • parted <device>

    Open the parted partition editor for a disk

  • mkfs.ext4 <device>

    Format a device with the ext4 filesystem

  • mkfs.vfat <device>

    Format a device with the FAT filesystem

  • mkswap <device>

    Set up a swap space on a device

  • swapon <device>

    Enable a swap space

  • swapoff <device>

    Disable a swap space

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

    Copy and convert data from input to output block by block

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

    Create a 100MB file filled with zeros

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

    Write an ISO image to a device

  • fsck <device>

    Check and repair a filesystem

  • e2fsck -f <device>

    Force a check of an ext2/3/4 filesystem

  • resize2fs <device>

    Resize an ext2/3/4 filesystem

Scheduling & Automation

  • crontab -e

    Edit the current user's crontab file

  • crontab -l

    List the current user's cron jobs

  • crontab -r

    Remove the current user's crontab file

  • crontab -u <user> -e

    Edit the crontab for a specific user

  • at <time>

    Schedule a command to run once at a specific time

  • atq

    List all pending at jobs

  • atrm <job>

    Remove a pending at job by its job number

  • systemctl start <service>

    Start a systemd service

  • systemctl stop <service>

    Stop a running systemd service

  • systemctl restart <service>

    Restart a systemd service

  • systemctl status <service>

    Check the status of a systemd service

  • systemctl enable <service>

    Enable a service to start automatically at boot

  • systemctl disable <service>

    Disable a service from starting at boot

  • systemctl list-units --type=service

    List all active systemd services

  • journalctl -u <service>

    View the logs for a specific systemd service

  • journalctl -f

    Follow the system journal in real-time

  • journalctl --since "<date>"

    Show journal entries since a specific date

Miscellaneous

  • history

    Show the command history for the current session

  • history -c

    Clear all command history

  • history | grep <command>

    Search through command history for a specific command

  • !<n>

    Re-run command number <n> from history

  • !!

    Re-run the most recently executed command

  • !<string>

    Re-run the most recent command starting with a string

  • alias <name>='<command>'

    Create a shortcut alias for a command

  • alias

    List all currently defined aliases

  • unalias <name>

    Remove a defined alias

  • man <command>

    Display the manual page for a command

  • man -k <keyword>

    Search manual page descriptions for a keyword

  • info <command>

    Display the info manual for a command

  • --help

    Display help information for most commands when appended

  • clear

    Clear the terminal screen

  • reset

    Reset the terminal to its initial state

  • exit

    Exit the current shell session

  • logout

    Log out of a login shell

  • script <file>

    Record a terminal session to a file

  • tmux

    Start a new tmux terminal multiplexer session

  • tmux new -s <name>

    Start a new named tmux session

  • tmux attach -t <name>

    Attach to an existing tmux session

  • tmux ls

    List all active tmux sessions

  • screen

    Start a new GNU screen session

  • screen -r

    Resume a detached screen session

  • xdg-open <file>

    Open a file with the default associated application

  • xclip -sel clip < <file>

    Copy file contents to the system clipboard

  • bc

    Open an interactive arbitrary precision calculator

  • bc -l

    Open bc with math library for floating point operations

  • factor <number>

    Print the prime factorization of a number

  • seq <start> <end>

    Generate a sequence of numbers from start to end

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

    Generate a sequence of numbers using a custom separator

  • yes

    Repeatedly output 'y' to auto-accept prompts

  • yes <string>

    Repeatedly output a custom string