Linux Basics: Commands

Understanding the fundamentals of commands available on Linux is critical to the success of an engineer. In this post, we’ll take a look at some of the commands available, define a category for them, describe their usage, and touch on their options.

Table of Contents

This is a long file, so here’s a table of contents.

File and Directory

Networking

User Management

Disk Management

Process and System

Archiving and Compression

Shell Utilities

File and Directory

File

cat

Description

The cat command is used to display the contents of files, concatenate multiple files together, and create new files by redirecting output.

Options

  • -n or --number: Number all output lines.
  • -b or --number-nonblank: Number non-blank output lines.
  • -s or --squeeze-blank: Suppress repeated empty output lines.
  • -E or --show-ends: Display a $ at the end of each line.
  • -T or --show-tabs: Display TAB characters as ^I.
  • -A or --show-all: Equivalent to -vET (shows all non-printing characters).

Examples

  • cat filename: Displays the contents of a single file.
      cat /etc/hosts
    
  • cat file1 file2: Displays the contents of multiple files sequentially.
  • cat file1 file2 > combined.txt: Concatenates multiple files and writes to a new file. If the “new” file already exists, it’s contents will be replaced by the files passed to cat.
  • cat file1 >> file2: Appends the contents of file1 to file2.
  • cat -n filename: Displays file contents with line numbers.
  • cat > file.txt: Creates a new file if it doesn’t exist, blanks out the file if it does. The end result will always be an empty file.
  • cat file1 | grep pattern: Pipes file contents to another command for processing.
      cat /var/log/syslog | grep "error"  # Searches for the term "error" and outputs lines containing it to the terminal
    

Description

The head command is used to display the first few lines of a file or input stream.

Options

  • -n or --lines: Specify the number of lines to display (default is 10).
  • -c or --bytes: Display the first N bytes instead of lines.
  • -v or --verbose: Always print file headers.
  • -q or --quiet or --silent: Never print file headers.

Examples

  • head filename: Displays the first 10 lines of a file.
  • head -n 20 filename: Displays the first 20 lines of a file.
  • head -5 filename: Displays the first 5 lines (short form of head -n 5 filename).
  • head file1 file2: Displays the first 10 lines of multiple files.
  • head -c 100 filename: Displays the first 100 bytes of a file.
  • cat filename | head -20: Pipes file contents to head to show first 20 lines.
    • Caution: This is inefficient for large files. cat reads and outputs the entire file, causing unnecessary I/O and short-term memory consumption. It is better to use head -20 filename instead, which stops reading after the first 20 lines.

less

Description

The less command is used to view file contents one page at a time, allowing forward and backward navigation through the file.

Options

  • -N or --LINE-NUMBERS: Display line numbers.
  • -S or --chop-long-lines: Chop long lines instead of wrapping.
  • -i or --ignore-case: Ignore case in searches.
  • -F or --quit-if-one-screen: Exit immediately if the file fits on one screen.
  • -X or --no-init: Don’t clear the screen on exit.

Examples

  • less filename: Opens a file for viewing with navigation controls.
  • less file1 file2: Opens multiple files for viewing (use :n for next, :p for previous).
  • cat filename | less: Pipes file contents to less for viewing.
  • less -N filename: Displays the file with line numbers.
  • Navigation in less: Use arrow keys, Page Up/Down, q to quit, /pattern to search forward, ?pattern to search backward.

tail

Description

The tail command is used to display the last few lines of a file or input stream, commonly used for monitoring log files.

Options

  • -n or --lines: Specify the number of lines to display (default is 10).
  • -f or --follow: Follow the file and display new lines as they are added (useful for log files).
  • -c or --bytes: Display the last N bytes instead of lines.
  • -F or --follow=name --retry: Like -f, but retries if the file is inaccessible.

Examples

  • tail filename: Displays the last 10 lines of a file.
      tail /var/log/syslog
    
  • tail -n 20 filename: Displays the last 20 lines of a file.
  • tail -5 filename: Displays the last 5 lines (short form of tail -n 5 filename).
  • tail -f filename: Follows the file and displays new lines as they are added (press Ctrl+C to exit).
  • tail -F filename: Follows the file and retries if it becomes inaccessible.
  • tail file1 file2: Displays the last 10 lines of multiple files.
  • cat filename | tail -20: Pipes file contents to tail to show last 20 lines.
    • Caution: This is inefficient for large files. cat reads and outputs the entire file, causing unnecessary I/O and short-term memory consumption. It is better to use tail -20 filename instead, which seeks directly to the end of the file.

touch

Description

The touch command is used to create new empty files or update the access and modification timestamps of existing files.

Options

  • -a or --time=atime: Change only the access time.
  • -m or --time=mtime: Change only the modification time.
  • -c or --no-create: Do not create the file if it does not exist.
  • -t: Use a specific time instead of the current time.
  • -r or --reference: Use the timestamp from a reference file.

Examples

  • touch filename: Creates a new empty file or updates the timestamp of an existing file.
  • touch file1 file2 file3: Creates multiple empty files.
  • touch -a filename: Updates only the access time of a file.
  • touch -m filename: Updates only the modification time of a file.
  • touch -t 202401011200 filename: Sets a specific timestamp (YYYYMMDDHHMM).
  • touch -r reference.txt target.txt: Sets the timestamp of target.txt to match reference.txt.

wc

Description

The wc command is used to count lines, words, and bytes in files or input streams.

Options

  • -l or --lines: Print only the number of lines.
  • -w or --words: Print only the number of words.
  • -c or --bytes: Print only the number of bytes.
  • -m or --chars: Print only the number of characters.
  • -L or --max-line-length: Print the length of the longest line.

Examples

  • wc filename: Displays the number of lines, words, and bytes in a file.
  • wc -l filename: Displays only the number of lines in a file.
  • wc -w filename: Displays only the number of words in a file.
  • wc -c filename: Displays only the number of bytes in a file.
  • wc file1 file2: Counts lines, words, and bytes for multiple files.
  • cat filename | wc -l: Pipes file contents to wc to count lines.
  • ls | wc -l: Counts the number of files in the current directory.

Directory

cd

Description

The cd command is used to change the current working directory to a specified directory, allowing users to navigate the filesystem.

Options

cd does not have options available, it simply accepts an argument of the directory you want to change to.

Examples

  • cd without arguments: Changes to the user’s home directory.
  • cd ~: Also changes to the current user’s home directory.
  • cd ~/path/to/directory: Changes to a path in the current user’s home directory.
      cd ~/src/sites/thelinux.pro
    
  • cd ~username: Changes to the specified user’s home directory.
      cd ~user2
    
  • cd -: Changes to the previous working directory.
  • cd ..: Moves up one directory (to the parent directory).
  • cd /path/to/directory: Changes to an absolute path starting at the root (/) of the filesystem.
      cd /var/log
    
  • cd path/to/directory: Changes to a relative path starting at the present working directory (pwd) of the filesystem. cd ../Documents # goes up one level then to the directory called Documents cd ../../Desktop # goes up two levels then to the directory called Desktop cd thelinux.pro # goes to a directory called thelinux.pro that is inside the present working directory (pwd) ```
  • cd .: Remains in the current directory (no effect).

mkdir

Description

The mkdir command is used to create new directories (folders) in the filesystem.

Options

  • -p or --parents: Create parent directories as needed and do not error if the directory already exists.
  • -v or --verbose: Display a message for each directory created.
  • -m or --mode: Set the file mode (permissions) for the created directories.
  • --help: Display help information.

Examples

  • mkdir directory_name: Creates a new directory in the current location.
  • mkdir dir1 dir2 dir3: Creates multiple directories at once.
      mkdir docs images scripts
    
  • mkdir -p path/to/directory: Creates a directory and all necessary parent directories.
      mkdir -p /home/user/projects/myapp/src
    
  • mkdir -p existing_dir/: Creates a directory if it doesn’t exist, does nothing if it already exists.
  • mkdir -m 755 directory_name: Creates a directory with specific permissions.
      mkdir -m 755 public_html
    
  • mkdir -pv path/to/directory: Verbosely creates a directory and all parent directories, showing each one created.

pwd

Description

The pwd command is used to print the current working directory, displaying the full path from the root of the filesystem.

Options

  • -L or --logical: Use logical path (follow symbolic links).
  • -P or --physical: Use physical path (resolve symbolic links to their actual paths).
  • --help: Display help information.

Examples

  • pwd: Displays the current working directory.
      pwd
      # Output: /home/user/projects
    
  • pwd -L: Displays the logical path (may include symbolic links).
  • pwd -P: Displays the physical path (resolves symbolic links to actual paths).
      cd /var/www
      pwd -P
      # Output: /usr/local/share/www (if /var/www is a symlink to /usr/local/share/www)
    

rmdir

Description

The rmdir command is used to remove empty directories from the filesystem. Unlike rm -r, rmdir only removes directories that are completely empty.

Options

  • -p or --parents: Remove parent directories if they become empty after removing the specified directory.
  • -v or --verbose: Display a message for each directory removed.
  • --ignore-fail-on-non-empty: Ignore failures when directories are not empty.
  • --help: Display help information.

Examples

  • rmdir directory_name: Removes an empty directory. Returns an error if the directory is not empty.
      rmdir empty_folder
    
  • rmdir dir1 dir2 dir3: Removes multiple empty directories at once.
      rmdir temp1 temp2 temp3
    
  • rmdir -p path/to/directory: Removes the directory and its parent directories if they become empty.
      rmdir -p /home/user/projects/myapp/src
    
  • rmdir -v directory_name: Verbosely removes an empty directory, showing confirmation.
      rmdir -v old_directory
      # Output: rmdir: removing directory, 'old_directory'
    

File & Directory

chmod

For more detailed examples, see this post: Linux Basics: Filesystem Permissions

Description

The chmod command is used to change the permissions (read, write, execute) of files and directories for the owner, group, and others.

Options

  • -R or --recursive: Change permissions recursively for directories and their contents.
  • -v or --verbose: Display a message for each file processed.
  • -c or --changes: Like verbose but only report when a change is made.
  • -f or --silent or --quiet: Suppress most error messages.

Examples

  • chmod 755 filename: Sets permissions using octal notation (owner: rwx, group: rx, others: rx).
      chmod 755 script.sh
    
  • chmod u+x filename: Adds execute permission for the owner.
  • chmod g-w filename: Removes write permission for the group.
  • chmod o+r filename: Adds read permission for others.
  • chmod a+x filename: Adds execute permission for all (owner, group, others).
  • chmod -R 644 directory/: Recursively sets permissions for all files in a directory.
      chmod -R 644 /var/www/html/
    
  • chmod 600 filename: Sets permissions so only the owner can read and write (common for sensitive files).

chown

For more detailed examples, see this post: Linux Basics: Filesystem Permissions

Description

The chown command is used to change the ownership of files and directories to a specified user and/or group.

Options

  • -R or --recursive: Change ownership recursively for directories and their contents.
  • -v or --verbose: Display a message for each file processed.
  • -c or --changes: Like verbose but only report when a change is made.
  • -h or --no-dereference: Affect symbolic links instead of the files they point to.

Examples

  • chown user filename: Changes the owner of a file to the specified user.
      chown www-data index.html
    
  • chown user:group filename: Changes both owner and group of a file.
      chown www-data:www-data index.html
    
  • chown :group filename: Changes only the group of a file.
      chown :www-data index.html
    
  • chown -R user:group directory/: Recursively changes ownership for all files in a directory.
      chown -R www-data:www-data /var/www/html/
    
  • chown user:group file1 file2: Changes ownership of multiple files at once.

cp

Description

The cp command is used to copy files and directories from one location to another.

Options

  • -r or -R or --recursive: Copy directories recursively.
  • -i or --interactive: Prompt before overwriting existing files.
  • -v or --verbose: Display what is being copied.
  • -p or --preserve: Preserve file attributes (mode, ownership, timestamps).
  • -u or --update: Copy only when the source file is newer than the destination file.
  • -f or --force: Force copy by removing existing destination files if needed.

Examples

  • cp source.txt destination.txt: Copies a file to a new location or name.
      cp file.txt backup.txt
    
  • cp file1 file2 directory/: Copies multiple files to a directory.
      cp file1.txt file2.txt /tmp/
    
  • cp -r source_dir/ destination_dir/: Recursively copies a directory and its contents.
      cp -r /home/user/docs/ /backup/
    
  • cp -i file.txt destination.txt: Prompts before overwriting if the destination exists.
  • cp -p file.txt backup.txt: Copies a file while preserving its attributes.
  • cp -u source.txt destination.txt: Only copies if the source is newer than the destination.

ln

Description

The ln command is used to create links between files, either hard links or symbolic (soft) links.

Options

  • -s or --symbolic: Create a symbolic link instead of a hard link.
  • -f or --force: Remove existing destination files.
  • -v or --verbose: Print the name of each linked file.
  • -i or --interactive: Prompt before removing existing files.

Examples

  • ln target linkname: Creates a hard link to a file.
      ln file.txt hardlink.txt
    
  • ln -s target linkname: Creates a symbolic link to a file or directory.
      ln -s /usr/bin/python3 python
    
  • ln -s /path/to/directory linkname: Creates a symbolic link to a directory.
      ln -s /var/www/html/ www
    
  • ln -sf target linkname: Forces creation of a symbolic link, overwriting if it exists.
  • ln -s ../file.txt linkname: Creates a symbolic link using a relative path.

ls

Description

The ls command is used to list files and directories in the current directory or specified location.

Options

  • -l or --long: Use a long listing format showing detailed information.
  • -a or --all: Show all files including hidden files (starting with .).
  • -h or --human-readable: Display file sizes in human-readable format (KB, MB, GB).
  • -t or --sort=time: Sort by modification time, newest first.
  • -r or --reverse: Reverse the order of the sort.
  • -R or --recursive: List subdirectories recursively.
  • -S or --sort=size: Sort by file size, largest first.
  • -d or --directory: List directories themselves, not their contents.

Examples

  • ls: Lists files and directories in the current directory.
  • ls -l: Lists files with detailed information (permissions, owner, size, date).
  • ls -la: Lists all files including hidden files with detailed information.
  • ls -lh: Lists files with human-readable file sizes.
  • ls directory/: Lists files in a specified directory.
      ls /var/log/
    
  • ls -lt: Lists files sorted by modification time, newest first.
  • ls -R: Recursively lists all files in the current directory and subdirectories.
  • ls *.txt: Lists only files matching a pattern.
      ls *.txt
    

mv

Description

The mv command is used to move or rename files and directories from one location to another.

Options

  • -i or --interactive: Prompt before overwriting existing files.
  • -v or --verbose: Display what is being moved.
  • -f or --force: Don’t prompt before overwriting existing files.
  • -u or --update: Move only when the source file is newer than the destination file.
  • -b or --backup: Create a backup of each existing destination file.

Examples

  • mv source.txt destination.txt: Renames a file or moves it to a new location.
      mv oldname.txt newname.txt
    
  • mv file.txt directory/: Moves a file into a directory.
      mv file.txt /tmp/
    
  • mv file1 file2 directory/: Moves multiple files to a directory.
      mv /home/user1/file1.txt file2.txt /backup/ # Moves file1.txt from /home/user1.txt and file2 from the present working directory (pwd) to a folder at the root of the filesystem called backup (/backup/).
    
  • mv -i file.txt destination.txt: Prompts before overwriting if the destination exists.
  • mv directory1/ directory2/: Renames or moves a directory.
      mv olddir/ newdir/
    
  • mv -v *.txt directory/: Verbosely moves all .txt files to a directory.

rm

Description

The rm command is used to remove (delete) files and directories from the filesystem.

Options

  • -r or -R or --recursive: Remove directories and their contents recursively.
  • -f or --force: Ignore nonexistent files and never prompt.
  • -i or --interactive: Prompt before each removal.
  • -v or --verbose: Display what is being removed.
  • -d or --dir: Remove empty directories.

Examples

  • rm filename: Removes a single file.
      rm oldfile.txt
    
  • rm file1 file2 file3: Removes multiple files.
      rm file1.txt file2.txt file3.txt
    
  • rm -r directory/: Recursively removes a directory and all its contents.
      rm -r old_directory/
    
  • rm -rf directory/: Forcefully and recursively removes a directory without prompting.
      rm -rf /tmp/old_files/      #removes old_files and all of it's contents from /tmp
    
  • rm -i filename: Prompts before removing each file.
  • rm *.txt: Removes all files matching a pattern.
      rm *.log                    # Removes all files in the present working directory (pwd) that end with .log
    
  • rm -d empty_dir/: Removes an empty directory.

Networking

Network Configuration

ifconfig

Description

The ifconfig command is used to configure, display, and manage network interface parameters for network interfaces.

Options

  • -a: Display all interfaces, including those that are down.
  • up: Activate the specified network interface.
  • down: Deactivate the specified network interface.
  • inet: Set the IP address for the interface.

Examples

  • ifconfig: Displays information about all active network interfaces.
  • ifconfig -a: Displays information about all interfaces, including inactive ones.
  • ifconfig eth0: Displays information about a specific interface.
      ifconfig eth0
    
  • ifconfig eth0 up: Activates a network interface.
  • ifconfig eth0 down: Deactivates a network interface.
  • ifconfig eth0 192.168.1.100: Sets the IP address for an interface.

ip

Description

The ip command is used to show or manipulate routing, network devices, interfaces, and tunnels. It is the modern replacement for ifconfig.

Options

  • addr or a: Manage IP addresses on devices.
  • link or l: Manage network interfaces.
  • route or r: Manage routing table.
  • show: Display information about network objects.

Examples

  • ip addr show: Displays all network interfaces and their IP addresses.
  • ip link show: Displays all network interfaces.
  • ip route show: Displays the routing table.
  • ip addr add 192.168.1.100/24 dev eth0: Adds an IP address to an interface.
  • ip link set eth0 up: Activates a network interface.
  • ip link set eth0 down: Deactivates a network interface.

Network Diagnostics

ping

Description

The ping command is used to test network connectivity between the local system and a remote host by sending ICMP echo request packets.

Options

  • -c count: Stop after sending the specified number of packets.
  • -i interval: Wait the specified number of seconds between sending each packet.
  • -t ttl: Set the Time To Live (TTL) value.
  • -W timeout: Time to wait for a response in seconds.

Examples

  • ping hostname: Continuously ping a host until interrupted (Ctrl+C).
      ping google.com
    
  • ping -c 4 hostname: Send 4 ping packets and then stop.
      ping -c 4 8.8.8.8
    
  • ping -i 2 hostname: Ping with a 2-second interval between packets.
  • ping -c 10 -i 1 hostname: Send 10 packets with 1-second intervals.

netstat

Description

The netstat command is used to display network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.

Options

  • -a or --all: Show all listening and non-listening sockets.
  • -t or --tcp: Show TCP connections.
  • -u or --udp: Show UDP connections.
  • -n or --numeric: Show numerical addresses instead of resolving hosts.
  • -p or --program: Show the PID and name of the program to which each socket belongs.
  • -l or --listening: Show only listening sockets.

Examples

  • netstat -a: Displays all active network connections.
  • netstat -tuln: Displays all listening TCP and UDP ports with numerical addresses.
      netstat -tuln
    
  • netstat -p: Displays connections with process information.
  • netstat -r: Displays the routing table.
  • netstat -i: Displays network interface statistics.

ss

Description

The ss command is used to display network socket information. It is the modern replacement for netstat and is faster and more efficient.

Options

  • -a or --all: Display all sockets.
  • -t or --tcp: Display TCP sockets.
  • -u or --udp: Display UDP sockets.
  • -l or --listening: Display only listening sockets.
  • -n or --numeric: Do not resolve service names.
  • -p or --processes: Show process information.

Examples

  • ss -a: Displays all sockets.
  • ss -tuln: Displays all listening TCP and UDP ports with numerical addresses.
      ss -tuln
    
  • ss -tulpn: Displays listening ports with process information.
  • ss -s: Displays summary statistics.

traceroute

Description

The traceroute command is used to display the route that packets take to reach a network host, showing each hop along the way.

Options

  • -n: Do not resolve IP addresses to hostnames.
  • -m max_ttl: Set the maximum number of hops (default is 30).
  • -w timeout: Set the timeout for each probe in seconds.

Examples

  • traceroute hostname: Traces the route to a hostname.
      traceroute google.com
    
  • traceroute -n hostname: Traces the route without resolving hostnames.
  • traceroute -m 15 hostname: Limits the trace to 15 hops maximum.

Network File Transfer

curl

Description

The curl command is used to transfer data from or to a server using various protocols (HTTP, HTTPS, FTP, etc.).

Options

  • -o filename: Write output to a file instead of stdout.
  • -O: Write output to a file with the same name as the remote file.
  • -L: Follow redirects.
  • -s or --silent: Silent mode, don’t show progress.
  • -v or --verbose: Verbose mode, show detailed information.
  • -H: Add a custom header to the request.

Examples

  • curl URL: Downloads and displays the content from a URL.
      curl https://example.com
    
  • curl -O URL: Downloads a file and saves it with the original filename.
      curl -O https://example.com/file.txt
    
  • curl -o filename URL: Downloads a file and saves it with a specific name.
      curl -o myfile.txt https://example.com/file.txt
    
  • curl -L URL: Follows redirects when downloading.
  • curl -s URL: Downloads silently without showing progress.

wget

Description

The wget command is used to download files from the web using HTTP, HTTPS, and FTP protocols.

Options

  • -O filename: Save the downloaded file with a specific name.
  • -c or --continue: Continue downloading a partially downloaded file.
  • -r or --recursive: Download recursively.
  • -P directory: Save files to a specific directory.
  • -q or --quiet: Quiet mode, suppress output.

Examples

  • wget URL: Downloads a file from a URL.
      wget https://example.com/file.txt
    
  • wget -O filename URL: Downloads and saves with a specific filename.
      wget -O myfile.txt https://example.com/file.txt
    
  • wget -c URL: Continues downloading a partially downloaded file.
  • wget -P /path/to/dir URL: Downloads a file to a specific directory.

User Management

User Information

whoami

Description

The whoami command displays the username of the current user.

Options

whoami does not have options available.

Examples

  • whoami: Displays the current username.
      whoami
      # Output: user1
    

id

Description

The id command displays user and group information for the current user or a specified user.

Options

  • -u or --user: Display only the user ID.
  • -g or --group: Display only the primary group ID.
  • -G or --groups: Display all group IDs.
  • -n or --name: Display names instead of numeric IDs.

Examples

  • id: Displays user and group information for the current user.
      id
      # Output: uid=1000(user1) gid=1000(group1) groups=1000(group1),1001(admin)
    
  • id username: Displays user and group information for a specific user.
      id user2
    
  • id -u: Displays only the user ID.
  • id -g: Displays only the primary group ID.
  • id -Gn: Displays all group names for the current user.

who

Description

The who command displays information about users currently logged into the system.

Options

  • -a or --all: Display all information.
  • -u: Display idle time and process ID.
  • -H or --heading: Print column headings.

Examples

  • who: Displays users currently logged in.
      who
    
  • who -a: Displays all available information about logged-in users.
  • who -u: Displays users with idle time and process information.

w

Description

The w command displays information about users currently logged in and what they are doing.

Options

  • -h or --no-header: Don’t print the header.
  • -s or --short: Use short format.
  • -f or --from: Toggle printing the from (remote hostname) field.

Examples

  • w: Displays users and their current processes.
      w
    
  • w username: Displays information about a specific user.
      w user1
    

User Management

useradd

Description

The useradd command is used to create a new user account on the system.

Options

  • -m or --create-home: Create the user’s home directory.
  • -s shell: Set the user’s login shell.
  • -G groups: Add the user to additional groups.
  • -d directory: Set the user’s home directory.
  • -u uid: Set the user ID.

Examples

  • useradd username: Creates a new user account.
      useradd newuser
    
  • useradd -m username: Creates a new user with a home directory.
      useradd -m newuser
    
  • useradd -m -s /bin/bash username: Creates a user with a home directory and bash shell.
  • useradd -m -G sudo,admin username: Creates a user and adds them to additional groups.

usermod

Description

The usermod command is used to modify an existing user account.

Options

  • -a or --append: Add the user to additional groups (use with -G).
  • -G groups: Set the list of supplementary groups.
  • -s shell: Change the user’s login shell.
  • -d directory: Change the user’s home directory.
  • -L or --lock: Lock the user’s password.
  • -U or --unlock: Unlock the user’s password.

Examples

  • usermod -s /bin/bash username: Changes a user’s login shell.
      usermod -s /bin/bash user1
    
  • usermod -aG sudo username: Adds a user to the sudo group.
      usermod -aG sudo user1
    
  • usermod -L username: Locks a user’s password.
  • usermod -U username: Unlocks a user’s password.

userdel

Description

The userdel command is used to delete a user account from the system.

Options

  • -r or --remove: Remove the user’s home directory and mail spool.
  • -f or --force: Force removal even if the user is logged in.

Examples

  • userdel username: Deletes a user account.
      userdel olduser
    
  • userdel -r username: Deletes a user account and removes their home directory.
      userdel -r olduser
    

passwd

Description

The passwd command is used to change a user’s password.

Options

  • -l or --lock: Lock the password of the specified account.
  • -u or --unlock: Unlock the password of the specified account.
  • -d or --delete: Delete the password for the specified account.
  • -S or --status: Display password status information.

Examples

  • passwd: Changes the current user’s password.
  • passwd username: Changes the password for a specific user (requires root).
      sudo passwd user1
    
  • passwd -l username: Locks a user’s password.
  • passwd -u username: Unlocks a user’s password.

su

Description

The su command is used to switch to another user account or become the superuser (root).

Options

  • - or -l or --login: Start a login shell (load user’s environment).
  • -c command: Execute a command as the specified user.
  • -s shell: Specify the shell to use.

Examples

  • su: Switches to the root user.
  • su username: Switches to another user account.
      su user2
    
  • su - username: Switches to another user with a login shell (loads their environment).
      su - user2
    
  • su -c "command" username: Executes a command as another user.
      su -c "ls -la" user2
    

sudo

Description

The sudo command allows a permitted user to execute a command as the superuser or another user, as specified in the sudoers file.

Options

  • -u user: Run the command as the specified user.
  • -i or --login: Run a login shell as the target user.
  • -s or --shell: Run the shell specified by the SHELL environment variable.
  • -v or --validate: Update the user’s timestamp, extending sudo timeout.

Examples

  • sudo command: Executes a command with root privileges.
      sudo apt update
    
  • sudo -u username command: Executes a command as another user.
      sudo -u www-data ls /var/www
    
  • sudo -i: Starts an interactive root shell.
  • sudo -v: Extends the sudo timeout without running a command.

Disk Management

Disk Information

df

Description

The df command displays information about filesystem disk space usage.

Options

  • -h or --human-readable: Display sizes in human-readable format (KB, MB, GB).
  • -T or --print-type: Display filesystem type.
  • -a or --all: Include filesystems with 0 blocks.
  • -i or --inodes: Display inode information instead of block usage.

Examples

  • df: Displays disk space usage for all mounted filesystems.
  • df -h: Displays disk space usage in human-readable format.
      df -h
    
  • df -hT: Displays disk space usage with filesystem types in human-readable format.
  • df -i: Displays inode usage instead of disk space.

du

Description

The du command estimates and displays disk space usage of files and directories.

Options

  • -h or --human-readable: Display sizes in human-readable format.
  • -s or --summarize: Display only a total for each argument.
  • -a or --all: Display counts for all files, not just directories.
  • -d depth or --max-depth=depth: Limit the depth of directory traversal.
  • --max-depth=0: Same as -s, summarize only.

Examples

  • du: Displays disk usage for the current directory and subdirectories.
  • du -h: Displays disk usage in human-readable format.
      du -h
    
  • du -sh directory/: Displays the total disk usage for a directory.
      du -sh /var/log
    
  • du -ah: Displays disk usage for all files and directories.
  • du -h --max-depth=1: Displays disk usage one level deep.

lsblk

Description

The lsblk command lists information about all available block devices.

Options

  • -a or --all: Include empty devices in output.
  • -f or --fs: Include filesystem information.
  • -o columns: Specify which columns to display.
  • -p or --paths: Print full device paths.

Examples

  • lsblk: Lists all block devices in a tree format.
      lsblk
    
  • lsblk -f: Lists block devices with filesystem information.
  • lsblk -a: Lists all block devices including empty ones.

Disk Operations

mount

Description

The mount command is used to attach a filesystem to the directory tree at a specified mount point.

Options

  • -t type: Specify the filesystem type.
  • -o options: Specify mount options.
  • -a: Mount all filesystems listed in /etc/fstab.
  • -l: Show labels in the output.

Examples

  • mount: Displays all currently mounted filesystems.
  • mount /dev/sdb1 /mnt: Mounts a device to a mount point.
      mount /dev/sdb1 /mnt
    
  • mount -t ext4 /dev/sdb1 /mnt: Mounts a device with a specific filesystem type.
  • mount -a: Mounts all filesystems listed in /etc/fstab.

umount

Description

The umount command is used to detach a filesystem from the directory tree.

Options

  • -l or --lazy: Lazy unmount (detach the filesystem now, clean up later).
  • -f or --force: Force unmount (may cause data loss).
  • -a or --all: Unmount all filesystems.

Examples

  • umount /mnt: Unmounts the filesystem mounted at /mnt.
      umount /mnt
    
  • umount /dev/sdb1: Unmounts a filesystem by device name.
  • umount -l /mnt: Performs a lazy unmount.

fdisk

Description

The fdisk command is used to create and manipulate disk partition tables.

Options

  • -l or --list: List partition tables for specified devices.
  • -s partition: Display the size of a partition.

Examples

  • fdisk -l: Lists all disk partitions.
      sudo fdisk -l
    
  • fdisk /dev/sda: Opens an interactive partition editor for a disk.
      sudo fdisk /dev/sda
    

Process and System

Process Management

ps

Description

The ps command displays information about currently running processes.

Options

  • -a or --all: Show processes for all users.
  • -u user: Show processes for a specific user.
  • -x: Show processes without controlling terminals.
  • -e or -A: Show all processes.
  • -f or --full: Show full format listing.
  • -l or --long: Show long format.
  • --forest: Display process tree.

Examples

  • ps: Displays processes for the current user.
  • ps aux: Displays all processes with detailed information.
      ps aux
    
  • ps -ef: Displays all processes in full format.
  • ps -u username: Displays processes for a specific user.
      ps -u user1
    
  • ps --forest: Displays processes in a tree format.

top

Description

The top command displays real-time information about running processes, including CPU and memory usage.

Options

  • -u user: Show processes for a specific user only.
  • -p pid: Monitor specific process IDs.
  • -n iterations: Exit after the specified number of iterations.
  • -d delay: Set the delay between updates in seconds.

Examples

  • top: Displays real-time process information (press ‘q’ to quit).
      top
    
  • top -u username: Shows processes for a specific user.
  • top -d 5: Updates every 5 seconds.

htop

Description

The htop command is an interactive process viewer, an enhanced version of top with a more user-friendly interface.

Options

  • -u user: Show processes for a specific user only.
  • -p pid: Show only processes with the specified PIDs.
  • -d delay: Set the delay between updates in seconds.

Examples

  • htop: Opens the interactive process viewer (press ‘q’ to quit).
      htop
    
  • htop -u username: Shows processes for a specific user.

kill

Description

The kill command sends a signal to a process, typically to terminate it.

Options

  • -l or --list: List all available signals.
  • -s signal: Specify the signal to send.
  • -9 or -KILL: Send the KILL signal (force kill).

Examples

  • kill PID: Sends the TERM signal to terminate a process.
      kill 1234
    
  • kill -9 PID: Forcefully kills a process.
      kill -9 1234
    
  • kill -l: Lists all available signals.
  • kill -s SIGTERM PID: Sends a specific signal to a process.

killall

Description

The killall command kills processes by name instead of by process ID.

Options

  • -i or --interactive: Ask for confirmation before killing.
  • -u user: Kill only processes owned by the specified user.
  • -9 or -KILL: Send the KILL signal (force kill).

Examples

  • killall process_name: Terminates all processes with the specified name.
      killall firefox
    
  • killall -9 process_name: Forcefully kills all processes with the specified name.
  • killall -i process_name: Interactively asks for confirmation before killing.

jobs

Description

The jobs command displays the status of jobs started in the current shell session.

Options

  • -l or --long: Display process IDs in addition to the normal information.
  • -p or --pid: Display only process IDs.
  • -r: Display only running jobs.
  • -s: Display only stopped jobs.

Examples

  • jobs: Displays all jobs in the current shell session.
      jobs
    
  • jobs -l: Displays jobs with process IDs.
  • jobs -r: Displays only running jobs.

bg

Description

The bg command resumes a suspended job in the background.

Options

bg accepts a job specification (e.g., %1) as an argument.

Examples

  • bg: Resumes the most recently suspended job in the background.
  • bg %1: Resumes job number 1 in the background.
      bg %1
    

fg

Description

The fg command brings a background job to the foreground.

Options

fg accepts a job specification (e.g., %1) as an argument.

Examples

  • fg: Brings the most recently backgrounded job to the foreground.
  • fg %1: Brings job number 1 to the foreground.
      fg %1
    

System Information

uname

Description

The uname command displays system information.

Options

  • -a or --all: Display all information.
  • -s or --kernel-name: Display the kernel name.
  • -r or --kernel-release: Display the kernel release.
  • -m or --machine: Display the machine hardware name.
  • -o or --operating-system: Display the operating system.

Examples

  • uname: Displays the kernel name.
  • uname -a: Displays all system information.
      uname -a
    
  • uname -r: Displays the kernel release version.
  • uname -m: Displays the machine architecture.

uptime

Description

The uptime command displays how long the system has been running, the number of users, and the system load average.

Options

  • -p or --pretty: Display uptime in a pretty format.
  • -s or --since: Display the system up since date.

Examples

  • uptime: Displays system uptime and load average.
      uptime
    
  • uptime -p: Displays uptime in a human-readable format.

free

Description

The free command displays information about system memory usage.

Options

  • -h or --human: Display sizes in human-readable format.
  • -m: Display sizes in megabytes.
  • -g: Display sizes in gigabytes.
  • -s seconds: Continuously display memory usage at specified intervals.

Examples

  • free: Displays memory usage in kilobytes.
  • free -h: Displays memory usage in human-readable format.
      free -h
    
  • free -m: Displays memory usage in megabytes.
  • free -s 5: Displays memory usage every 5 seconds.

Archiving and Compression

Archiving

tar

Description

The tar command is used to create, extract, and manipulate tar archives (tape archives).

Options

  • -c or --create: Create a new archive.
  • -x or --extract: Extract files from an archive.
  • -f filename or --file=filename: Specify the archive filename.
  • -v or --verbose: Verbose mode, show files being processed.
  • -z or --gzip: Filter the archive through gzip.
  • -j or --bzip2: Filter the archive through bzip2.
  • -t or --list: List the contents of an archive.
  • -C directory: Change to the specified directory before extracting.

Examples

  • tar -cf archive.tar files/: Creates a tar archive.
      tar -cf backup.tar /home/user/docs/
    
  • tar -xvf archive.tar: Extracts files from a tar archive verbosely.
      tar -xvf backup.tar
    
  • tar -czf archive.tar.gz files/: Creates a gzip-compressed tar archive.
      tar -czf backup.tar.gz /home/user/docs/
    
  • tar -xzf archive.tar.gz: Extracts a gzip-compressed tar archive.
      tar -xzf backup.tar.gz
    
  • tar -tf archive.tar: Lists the contents of a tar archive.
  • tar -xzf archive.tar.gz -C /tmp/: Extracts to a specific directory.

zip

Description

The zip command is used to create and manipulate zip archives.

Options

  • -r or --recurse-paths: Recursively include directories.
  • -v or --verbose: Verbose mode.
  • -q or --quiet: Quiet mode.
  • -d: Delete entries from a zip archive.
  • -u: Update entries in a zip archive.

Examples

  • zip archive.zip file1 file2: Creates a zip archive with specified files.
      zip backup.zip file1.txt file2.txt
    
  • zip -r archive.zip directory/: Creates a zip archive recursively.
      zip -r backup.zip /home/user/docs/
    
  • zip -d archive.zip file1: Deletes a file from a zip archive.

unzip

Description

The unzip command is used to extract files from zip archives.

Options

  • -l or --list: List the contents of a zip archive.
  • -d directory: Extract files to a specific directory.
  • -o: Overwrite files without prompting.
  • -q or --quiet: Quiet mode.

Examples

  • unzip archive.zip: Extracts files from a zip archive.
      unzip backup.zip
    
  • unzip -l archive.zip: Lists the contents of a zip archive.
  • unzip archive.zip -d /tmp/: Extracts files to a specific directory.
      unzip backup.zip -d /tmp/
    

Compression

gzip

Description

The gzip command is used to compress files using the gzip compression algorithm.

Options

  • -d or --decompress: Decompress files.
  • -k or --keep: Keep the original file.
  • -r or --recursive: Recursively compress files in directories.
  • -v or --verbose: Verbose mode.
  • -l or --list: List compressed file information.

Examples

  • gzip filename: Compresses a file (replaces original with .gz file).
      gzip largefile.txt
    
  • gzip -d filename.gz: Decompresses a gzip file.
      gzip -d largefile.txt.gz
    
  • gzip -k filename: Compresses a file but keeps the original.
  • gzip -r directory/: Recursively compresses all files in a directory.

gunzip

Description

The gunzip command is used to decompress files compressed with gzip.

Options

  • -k or --keep: Keep the compressed file.
  • -r or --recursive: Recursively decompress files in directories.
  • -v or --verbose: Verbose mode.

Examples

  • gunzip filename.gz: Decompresses a gzip file.
      gunzip largefile.txt.gz
    
  • gunzip -k filename.gz: Decompresses but keeps the compressed file.

bzip2

Description

The bzip2 command is used to compress files using the bzip2 compression algorithm.

Options

  • -d or --decompress: Decompress files.
  • -k or --keep: Keep the original file.
  • -v or --verbose: Verbose mode.

Examples

  • bzip2 filename: Compresses a file (replaces original with .bz2 file).
      bzip2 largefile.txt
    
  • bzip2 -d filename.bz2: Decompresses a bzip2 file.
      bzip2 -d largefile.txt.bz2
    
  • bzip2 -k filename: Compresses a file but keeps the original.

bunzip2

Description

The bunzip2 command is used to decompress files compressed with bzip2.

Options

  • -k or --keep: Keep the compressed file.
  • -v or --verbose: Verbose mode.

Examples

  • bunzip2 filename.bz2: Decompresses a bzip2 file.
      bunzip2 largefile.txt.bz2
    

Shell Utilities

Text Processing

grep

Description

The grep command searches for patterns in text and displays matching lines.

Options

  • -i or --ignore-case: Ignore case distinctions.
  • -r or -R or --recursive: Recursively search directories.
  • -v or --invert-match: Invert the match (show non-matching lines).
  • -n or --line-number: Show line numbers.
  • -c or --count: Count matching lines.
  • -l or --files-with-matches: Show only filenames with matches.
  • -E or --extended-regexp: Use extended regular expressions.

Examples

  • grep pattern filename: Searches for a pattern in a file.
      grep "error" /var/log/syslog
    
  • grep -i pattern filename: Case-insensitive search.
      grep -i "error" logfile.txt
    
  • grep -r pattern directory/: Recursively searches for a pattern in a directory.
      grep -r "function" /home/user/scripts/
    
  • grep -n pattern filename: Shows line numbers with matches.
  • grep -v pattern filename: Shows lines that don’t match the pattern.

sed

Description

The sed command is a stream editor used to perform text transformations on input streams.

Options

  • -i: Edit files in place.
  • -n or --quiet: Suppress automatic printing of pattern space.
  • -e script: Add the script to the commands to be executed.
  • -f script-file: Add the contents of script-file to the commands.

Examples

  • sed 's/old/new/g' filename: Replaces all occurrences of “old” with “new” in a file.
      sed 's/foo/bar/g' file.txt
    
  • sed -i 's/old/new/g' filename: Replaces text in place (modifies the file).
      sed -i 's/foo/bar/g' file.txt
    
  • sed 's/old/new/' filename: Replaces only the first occurrence on each line.
  • sed -n '5p' filename: Prints only line 5.
      sed -n '5p' file.txt
    

awk

Description

The awk command is a pattern scanning and processing language used for text processing and data extraction.

Options

  • -F separator: Specify the field separator.
  • -f script-file: Read awk commands from a file.
  • -v var=value: Assign a value to a variable.

Examples

  • awk '{print $1}' filename: Prints the first field of each line.
      awk '{print $1}' /etc/passwd
    
  • awk -F: '{print $1}' filename: Uses colon as field separator.
      awk -F: '{print $1}' /etc/passwd
    
  • awk '/pattern/ {print}' filename: Prints lines matching a pattern.
      awk '/error/ {print}' logfile.txt
    
  • awk '{sum+=$1} END {print sum}' filename: Calculates the sum of the first column.

sort

Description

The sort command sorts lines of text files.

Options

  • -r or --reverse: Reverse the sort order.
  • -n or --numeric-sort: Sort numerically.
  • -u or --unique: Remove duplicate lines.
  • -k field: Sort by a specific field.
  • -t separator: Specify the field separator.

Examples

  • sort filename: Sorts lines in a file alphabetically.
      sort names.txt
    
  • sort -r filename: Sorts in reverse order.
  • sort -n filename: Sorts numerically.
      sort -n numbers.txt
    
  • sort -u filename: Sorts and removes duplicates.
  • sort -t: -k3 filename: Sorts by the third field using colon as separator.

uniq

Description

The uniq command filters out adjacent duplicate lines from input.

Options

  • -c or --count: Prefix lines with the number of occurrences.
  • -d or --repeated: Show only duplicate lines.
  • -u or --unique: Show only unique lines.
  • -i or --ignore-case: Ignore case when comparing.

Examples

  • uniq filename: Removes adjacent duplicate lines.
      uniq file.txt
    
  • sort filename | uniq: Removes all duplicate lines (requires sorting first).
      sort file.txt | uniq
    
  • uniq -c filename: Shows count of each unique line.
      uniq -c file.txt
    
  • uniq -d filename: Shows only duplicate lines.

cut

Description

The cut command extracts sections from each line of input.

Options

  • -d delimiter: Specify the field delimiter.
  • -f fields: Specify which fields to extract.
  • -c characters: Extract specific characters.

Examples

  • cut -d: -f1 filename: Extracts the first field using colon as delimiter.
      cut -d: -f1 /etc/passwd
    
  • cut -d: -f1,3 filename: Extracts the first and third fields.
  • cut -c1-10 filename: Extracts characters 1 through 10.
      cut -c1-10 file.txt
    

tr

Description

The tr command translates or deletes characters.

Options

  • -d: Delete characters.
  • -s: Squeeze repeated characters.
  • -c: Complement the set of characters.

Examples

  • tr 'a-z' 'A-Z' < filename: Converts lowercase to uppercase.
      tr 'a-z' 'A-Z' < file.txt
    
  • tr -d '0-9' < filename: Deletes all digits.
      tr -d '0-9' < file.txt
    
  • tr -s ' ' < filename: Squeezes multiple spaces into single spaces.

Other Utilities

find

Description

The find command searches for files and directories in a directory hierarchy.

Options

  • -name pattern: Search for files matching a name pattern.
  • -type type: Search for files of a specific type (f=file, d=directory).
  • -size size: Search for files of a specific size.
  • -mtime days: Search for files modified within a certain number of days.
  • -exec command {} \;: Execute a command on found files.
  • -delete: Delete found files.

Examples

  • find . -name "*.txt": Finds all .txt files in the current directory and subdirectories.
      find . -name "*.txt"
    
  • find /home -type f -name "*.log": Finds all log files in /home.
      find /home -type f -name "*.log"
    
  • find . -type d: Finds all directories in the current location.
  • find . -size +100M: Finds files larger than 100MB.
      find . -size +100M
    
  • find . -mtime -7: Finds files modified in the last 7 days.
  • find . -name "*.tmp" -delete: Finds and deletes all .tmp files.

which

Description

The which command locates a command by searching the directories in the PATH environment variable.

Options

  • -a: Show all matching executables in PATH.

Examples

  • which command: Shows the path to a command.
      which python
    
  • which -a command: Shows all instances of a command in PATH.

whereis

Description

The whereis command locates the binary, source, and manual page files for a command.

Options

  • -b: Search only for binaries.
  • -m: Search only for manual pages.
  • -s: Search only for sources.

Examples

  • whereis command: Shows the location of a command’s binary, source, and manual pages.
      whereis python
    
  • whereis -b command: Shows only the binary location.

history

Description

The history command displays the command history for the current shell session.

Options

  • -c: Clear the history list.
  • -d offset: Delete the history entry at the specified offset.
  • -a: Append history lines to the history file.

Examples

  • history: Displays the command history.
      history
    
  • history | grep pattern: Searches the history for a pattern.
      history | grep "apt"
    
  • history -c: Clears the command history.
  • !n: Executes command number n from history.
      !42
    

alias

Description

The alias command creates shortcuts or abbreviations for commands.

Options

alias does not have standard options, but accepts name=value pairs.

Examples

  • alias: Lists all current aliases.
  • alias ll='ls -la': Creates an alias for a command.
      alias ll='ls -la'
    
  • alias grep='grep --color=auto': Creates an alias with options.
  • unalias alias_name: Removes an alias.
      unalias ll
    

echo

Description

The echo command displays a line of text or the value of variables.

Options

  • -n: Do not output a trailing newline.
  • -e: Enable interpretation of backslash escapes.
  • -E: Disable interpretation of backslash escapes (default).

Examples

  • echo "Hello World": Displays text.
      echo "Hello World"
    
  • echo $VARIABLE: Displays the value of a variable.
      echo $HOME
    
  • echo -e "Line 1\nLine 2": Interprets escape sequences.
      echo -e "Line 1\nLine 2"
    
  • echo -n "No newline": Displays text without a trailing newline.

date

Description

The date command displays or sets the system date and time.

Options

  • -d string: Display the time described by the string.
  • -s string: Set the system date and time.
  • +format: Format the output using a format string.

Examples

  • date: Displays the current date and time.
      date
    
  • date +"%Y-%m-%d": Displays the date in a specific format.
      date +"%Y-%m-%d"
    
  • date +"%H:%M:%S": Displays only the time.
      date +"%H:%M:%S"