20 min read

Linux Learning Notes

Linux Learning Notes

Welcome to my Linux learning notes. These notes cover Linux fundamentals through advanced system administration topics.


Directory Structure (/ Directory)

πŸ”§ System and Configuration

FolderMeaning
/binEssential binaries (commands) needed for the system to boot and run (e.g., ls, cp, mv)
/sbinSystem binaries for root/admin tasks (e.g., reboot, fsck)
/etcConfiguration files (e.g., network, services, users, passwords)
/lib, /lib64Libraries needed by binaries in /bin and /sbin
/bootFiles needed to boot the system (e.g., the kernel, GRUB)
/devSpecial files for devices (e.g., /dev/sda for disks)
/procVirtual filesystem with kernel and process info (e.g., /proc/cpuinfo)
/sysVirtual filesystem with hardware and kernel info
/runRuntime data for processes after boot (temporary, stored in RAM)

πŸ§‘β€πŸ’» Users and Applications

FolderMeaning
/homeHome directories of users (e.g., /home/alex)
/rootHome directory for the root user (not in /home)
/usrUser-installed software and data (like /usr/bin, /usr/lib, etc.)
/optOptional software packages (often 3rd party)
/varVariable data like logs, mail, databases (e.g., /var/log)
/mediaMount point for external drives (e.g., USB, CDs)
/mntTemporary mount point (used by admins to mount anything manually)
/srvData for services like web or FTP servers (e.g., /srv/http)

πŸ—‘οΈ Temporary Stuff

FolderMeaning
/tmpTemporary files, usually cleared on reboot

Understanding Linux Basics

File and Directory Management

1. ls - List Files and Directories

  • Purpose: Displays the files and directories in your current directory.
  • Usage:
    • ls – List files in the current directory.
    • ls -l – List files in long format (shows permissions, owner, file size, etc.).
    • ls -a – List all files, including hidden files (those starting with a dot ., like .bashrc).

2. cd - Change Directory

  • Purpose: Change the current working directory.
  • Usage:
    • cd /path/to/directory – Go to a specific directory (absolute path).
    • cd directory_name – Go to a subdirectory inside your current location.
    • cd .. – Move up one level (parent directory).
    • cd ~ – Go to your home directory (shortcut).

3. pwd - Print Working Directory

  • Purpose: Shows the full path of your current directory.
  • Usage:
    • pwd – Shows your current directory’s path.

4. mkdir - Make Directory

  • Purpose: Creates a new directory.
  • Usage:
    • mkdir directory_name – Creates a new directory.
    • mkdir -p path/to/directory – Create parent directories if they don’t exist.

5. rmdir - Remove Empty Directory

  • Purpose: Removes an empty directory.
  • Usage:
    • rmdir directory_name – Removes the empty directory.

6. rm - Remove Files or Directories

  • Purpose: Delete files or directories.
  • Usage:
    • rm file_name – Deletes a file.
    • rm -r directory_name – Deletes a directory and all its contents (be careful!).
    • rm -f file_name – Force delete without asking for confirmation.

7. cp - Copy Files or Directories

  • Purpose: Copies files or directories from one place to another.
  • Usage:
    • cp source_file destination – Copy a file to a new location.
    • cp -r source_directory destination – Copy a directory and its contents.

8. mv - Move or Rename Files/Directories

  • Purpose: Moves files or directories, or renames them.
  • Usage:
    • mv source_file destination – Move or rename a file.
    • mv old_name new_name – Rename a file or directory.

9. touch - Create a New Empty File

  • Purpose: Creates an empty file or updates the timestamp of an existing file.
  • Usage:
    • touch filename – Creates a new empty file or updates the file’s last modified time.

File Content Operations

10. cat - Concatenate and Display File Contents

  • Purpose: Shows the contents of a file on the screen.
  • Usage:
    • cat filename – Display the content of the file.
    • cat file1 file2 – Concatenate and display content from multiple files.

11. more - View File Contents Page-by-Page

  • Purpose: View content of a file one page at a time (useful for large files).
  • Usage:
    • more filename – View file contents one page at a time.
    • Use space to move to the next page and q to quit.

12. less - View File Contents (Improved Version of more)

  • Purpose: Similar to more but gives more control, like scrolling up and down.
  • Usage:
    • less filename – View file contents and scroll through.
    • Use arrow keys to scroll up/down, q to quit.

13. head - View the First Few Lines of a File

  • Purpose: Displays the first 10 lines (by default) of a file.
  • Usage:
    • head filename – Show the first 10 lines of a file.
    • head -n 20 filename – Show the first 20 lines of a file.

14. tail - View the Last Few Lines of a File

  • Purpose: Displays the last 10 lines (by default) of a file.
  • Usage:
    • tail filename – Show the last 10 lines of a file.
    • tail -n 20 filename – Show the last 20 lines of a file.
    • tail -f filename – View a file and keep updating as it grows (useful for log files).

15. file - Identify File Type

  • Purpose: Identifies the file type (e.g., text, executable, image).
  • Usage:
    • file filename – Shows the type of file.

Search and Find

16. find - Search for Files and Directories

  • Purpose: Finds files or directories based on conditions like name, size, date, etc.
  • Usage:
    • find /path/to/search -name "filename" – Search for files with a specific name.
    • find /path/to/search -type d – Search for directories only.
    • find /path/to/search -size +1G – Find files larger than 1GB.

17. grep - Search for Text in Files

  • Purpose: Search for specific text within files.
  • Usage:
    • grep "search_term" filename – Find lines in the file that contain the search term.
    • grep -r "search_term" /path/to/dir – Search recursively in a directory.

File Permissions and Ownership

18. chmod - Change File Permissions

  • Purpose: Changes the read, write, and execute permissions of a file or directory.
  • Usage:
    • chmod 755 filename – Set read, write, execute permissions for owner and read, execute for others.
    • chmod u+x filename – Add execute permission to the file for the owner.

19. chown - Change File Ownership

  • Purpose: Change the owner and/or group of a file or directory.
  • Usage:
    • chown user:group filename – Change the owner and group of a file.
    • chown user filename – Change the owner of a file.

20. chgrp - Change Group Ownership

  • Purpose: Change the group ownership of a file or directory.
  • Usage:
    • chgrp group filename – Change the group of a file.

System Utilities

21. man - Manual Pages (Help)

  • Purpose: View the manual or documentation for a command.
  • Usage:
    • man command – View the manual for a specific command.
    • Example: man ls – Shows the manual for the ls command.

22. echo - Print Text or Variables

  • Purpose: Print text to the terminal, or show the value of a variable.
  • Usage:
    • echo "Hello, World!" – Prints β€œHello, World!” to the screen.
    • echo $HOME – Prints the value of the HOME variable (your home directory path).

23. sudo - Execute a Command as a Superuser

  • Purpose: Execute commands that require administrative (root) privileges.
  • Usage:
    • sudo command – Run a command with superuser privileges.
    • Example: sudo apt update – Update package lists (on Debian-based systems like Ubuntu).

24. exit - Exit the Terminal

  • Purpose: Close the current terminal session.
  • Usage:
    • exit – Exit the terminal (or close the terminal window).

Package Managers

Package managers are tools used to install, update, and remove software packages in Linux.

APT (Advanced Package Tool) – Debian-based systems (e.g., Ubuntu)

  • sudo apt update – Update package lists.
  • sudo apt install package_name – Install a package.
  • sudo apt remove package_name – Remove a package.
  • sudo apt upgrade – Upgrade installed packages.

YUM/DNF – Red Hat-based systems (e.g., Fedora, CentOS)

  • sudo yum install package_name – Install a package (older systems).
  • sudo dnf install package_name – Install a package (Fedora and newer CentOS).
  • sudo yum remove package_name – Remove a package.
  • sudo dnf upgrade – Upgrade installed packages.

Zypper – SUSE-based systems

  • sudo zypper install package_name – Install a package.
  • sudo zypper remove package_name – Remove a package.
  • sudo zypper update – Upgrade installed packages.

Environment Variables

Environment variables store information about the system environment and configuration.

Common Environment Variables:

  • HOME – Your home directory (e.g., /home/username).
  • USER – The current user.
  • PATH – A list of directories where executable programs are stored.
  • SHELL – The path of the current shell (e.g., /bin/bash).
  • LANG – The system’s language settings (e.g., en_US.UTF-8).

Viewing Environment Variables:

  • echo $VARIABLE_NAME – Show the value of an environment variable.
  • Example: echo $PATH – Displays the directories listed in the PATH variable.

Setting Environment Variables:

  • export VARIABLE_NAME=value – Set an environment variable temporarily.
  • Example: export EDITOR=nano – Set nano as the default text editor for the session.

Text Editors

Nano

  • Purpose: A simple terminal-based text editor.
  • Usage:
    • nano filename – Open a file in the nano editor.
  • Commands:
    • Ctrl + O – Save the file.
    • Ctrl + X – Exit the editor.
    • Ctrl + K – Cut a line.
    • Ctrl + U – Paste a line.

Vim

  • Purpose: A powerful, mode-based text editor.
  • Usage:
    • vim filename – Open a file in vim.
  • Commands:
    • i – Enter insert mode (for editing).
    • Esc – Exit insert mode.
    • :w – Save the file.
    • :q – Quit vim.
    • :wq – Save and quit.

Tips and Tricks

  • Tab Completion: When typing commands or file names, press Tab to auto-complete.
  • Up/Down Arrow: Use the up and down arrow keys to scroll through your previous commands.
  • Ctrl + C: Stops a running command or process.
  • Ctrl + Z: Puts a process in the background (suspend it).

User & System Administration

User Management

1. useradd – Add a New User

  • Purpose: Create a new user on the system.
  • Usage:
    sudo useradd username
    sudo useradd -m -s /bin/bash username  # Create user with home directory and specific shell
  • Note: m creates the home directory, and s specifies the shell.

2. usermod – Modify an Existing User

  • Purpose: Modify user account settings.
  • Usage:
    sudo usermod -aG groupname username  # Add user to a group
    sudo usermod -L username  # Lock user account
    sudo usermod -U username  # Unlock user account

3. userdel – Delete a User

  • Purpose: Remove a user from the system.
  • Usage:
    sudo userdel username  # Remove user but not their home directory
    sudo userdel -r username  # Remove user and their home directory

Group Management

4. groupadd – Add a New Group

  • Purpose: Create a new group.
  • Usage:
    sudo groupadd groupname

5. groupdel – Delete a Group

  • Purpose: Remove a group from the system.
  • Usage:
    sudo groupdel groupname

Password Management

6. passwd – Change User Password

  • Purpose: Change a user’s password.
  • Usage:
    sudo passwd username  # Change password of a specific user
    passwd  # Change the password of the current user

7. chage – Change User Password Expiry Information

  • Purpose: Modify the password expiry details for a user.
  • Usage:
    sudo chage -l username  # List password expiry information
    sudo chage -M 90 username  # Set password expiry to 90 day

User Information

8. id – Display User and Group Information

  • Purpose: Show user and group information for a user.
  • Usage:
    id username  # Show user and group info for username

9. groups – Show Groups a User Belongs To

  • Purpose: List all the groups a user is a part of.
  • Usage:
    groups username  # Show groups for a user

Disk Management

Disk Space Usage

1. df – Display Disk Space Usage

  • Purpose: Shows disk space usage on mounted filesystems.
  • Usage:
    • df – Show disk space usage.
    • df -h – Show disk space in a human-readable format (MB, GB).

2. du – Disk Usage of Files and Directories

  • Purpose: Shows disk usage for files or directories.
  • Usage:
    • du filename – Show the disk usage of a file.
    • du -sh /path/to/directory – Show total disk usage of a directory in a human-readable format.

Partition Management

3. fdisk – Partition Table Manipulation

  • Purpose: Create, delete, or modify disk partitions.
  • Usage:
    • sudo fdisk -l – List all partitions on the system.
    • sudo fdisk /dev/sda – Open partitioning tool for a specific disk (replace /dev/sda with your disk).

Mounting Filesystems

4. mount – Mount a Filesystem

  • Purpose: Mount a storage device or partition.
  • Usage:
    • sudo mount /dev/sda1 /mnt – Mount a partition (/dev/sda1) to a directory (/mnt).
    • mount – List all mounted filesystems.

5. umount – Unmount a Filesystem

  • Purpose: Unmount a filesystem or device.
  • Usage:
    • sudo umount /mnt – Unmount the device mounted at /mnt.

Block Devices

6. lsblk – List Block Devices

  • Purpose: Lists all block devices (like hard drives, partitions).
  • Usage:
    • lsblk – List block devices with details like size and mount point.

Filesystem Operations

7. mkfs – Create a Filesystem

  • Purpose: Create a new filesystem on a partition.
  • Usage:
    • sudo mkfs.ext4 /dev/sda1 – Format /dev/sda1 with the ext4 filesystem.

8. fsck – File System Check

  • Purpose: Check and repair filesystems.
  • Usage:
    • sudo fsck /dev/sda1 – Check and repair the filesystem on /dev/sda1.

Security Administration

File Permissions and Ownership

1. chmod – Change File Permissions

  • Purpose: Change file permissions for users (read, write, execute).
  • Usage:
    chmod 755 file  # rwxr-xr-x permissions for the file
    chmod u+x file  # Add execute permission for the user
    chmod -R 777 dir  # Recursively set permissions to 777 (rwx for all)

2. chown – Change File Owner and Group

  • Purpose: Change the owner and/or group of a file or directory.
  • Usage:
    sudo chown user:group file  # Change owner and group
    sudo chown -R user:group dir  # Change ownership recursively

3. chgrp – Change Group Ownership

  • Purpose: Change the group ownership of a file or directory.
  • Usage:
    sudo chgrp group file  # Change the group of the file

4. setfacl – Set File Access Control Lists

  • Purpose: Set more granular file permissions (for specific users/groups).
  • Usage:
    setfacl -m u:username:rwx file  # Grant read, write, execute to user
    getfacl file  # View ACLs for a file

File Integrity & Auditing

5. auditd – Linux Audit Daemon

  • Purpose: Record security-relevant events.
  • Usage:
    • Install the auditing tools: sudo apt install auditd
    • Configure logging: sudo auditctl -w /etc/passwd -p wa (Monitor changes to /etc/passwd).
    • View logs: sudo ausearch -f /etc/passwd

6. AIDE – Advanced Intrusion Detection Environment

  • Purpose: Check system files for integrity and changes.
  • Usage:
    • Install: sudo apt install aide
    • Initialize database: sudo aideinit
    • Check file integrity: sudo aide --check

Firewalls and Security

7. ufw – Uncomplicated Firewall

  • Purpose: Manage firewall settings in a simple way.
  • Usage:
    sudo ufw enable  # Enable firewall
    sudo ufw disable  # Disable firewall
    sudo ufw allow 22  # Allow SSH (port 22)
    sudo ufw deny 80  # Block HTTP (port 80)
    sudo ufw status  # Check firewall status

8. iptables – Configure Linux Kernel Firewall

  • Purpose: Advanced firewall configuration.
  • Usage:
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT  # Allow SSH
    sudo iptables -A INPUT -p tcp --dport 80 -j DROP  # Block HTTP
    sudo iptables -L  # List firewall rules

9. fail2ban – Intrusion Prevention Tool

  • Purpose: Protect from brute-force attacks by banning IPs.
  • Usage:
    • Install: sudo apt install fail2ban
    • Check status: sudo fail2ban-client status
    • Configure: Edit /etc/fail2ban/jail.local

Process Management

Process Viewing and Control

1. ps – Display Processes

  • Purpose: Shows a snapshot of current processes.
  • Usage:
    • ps – Display processes for the current shell.
    • ps aux – Show all processes running on the system.
    • ps -ef – Display process details in a full format.

2. top – Task Manager

  • Purpose: Provides a dynamic view of system processes.
  • Usage:
    • top – Start the task manager. Shows CPU usage, memory usage, and more.
    • q – Quit the top command.

3. kill – Terminate a Process

  • Purpose: Kill a process by PID (Process ID).
  • Usage:
    • kill PID – Kill a process using its PID.
    • kill -9 PID – Force kill a process (use with caution).

4. htop – Improved Task Manager

  • Purpose: An interactive process viewer (more user-friendly than top).
  • Usage:
    • htop – Start the htop process viewer.
    • Use arrow keys to navigate and F9 to kill a process.

Job Control

5. bg – Resume a Job in the Background

  • Purpose: Resume a paused job in the background.
  • Usage:
    • bg – Run the most recent job in the background.
    • bg %1 – Run job number 1 in the background.

6. fg – Bring a Job to the Foreground

  • Purpose: Bring a background job to the foreground.
  • Usage:
    • fg – Bring the most recent job to the foreground.
    • fg %1 – Bring job number 1 to the foreground.

7. jobs – List Background Jobs

  • Purpose: Show a list of jobs running in the background.
  • Usage:
    • jobs – List jobs with their status.

Process Priority

8. nice & renice – Change Process Priority

  • Purpose: Set or change the priority of a process.
  • Usage:
    • nice -n 10 command – Start a command with lower priority.
    • renice -n 10 PID – Change the priority of a running process.

Networking in Linux

Basic Networking Commands

1. ip – View or Configure Network Interfaces

  • Purpose: Shows or configures network interfaces and routing.
  • Usage:
    • ip addr – Display network interface details (IP addresses).
    • ip link – Show or manipulate network interfaces.
    • ip route – Show or modify the routing table.

2. ping – Test Network Connectivity

  • Purpose: Sends ICMP echo requests to test connectivity.
  • Usage:
    • ping hostname_or_IP – Ping a host to check if it’s reachable.
    • ping -c 4 google.com – Ping Google 4 times and then stop.

3. traceroute – Trace the Route Packets Take

  • Purpose: Shows the route packets take to a network host.
  • Usage:
    • traceroute google.com – Trace the route to Google’s servers.

4. netstat – Network Statistics

  • Purpose: Displays network connections, routing tables, and interface statistics.
  • Usage:
    • netstat – Show current network connections.
    • netstat -tuln – Show listening ports.

5. ifconfig – Configure Network Interfaces

  • Purpose: Display or configure network interfaces.
  • Usage:
    • ifconfig – Show network interface details.
    • ifconfig eth0 up – Bring the interface eth0 up.

Remote Access

6. ssh – Secure Shell for Remote Login

  • Purpose: Connect to a remote machine securely.
  • Usage:
    • ssh user@hostname_or_IP – Connect to a remote server.
    • Example: ssh alice@192.168.1.100

7. scp – Secure Copy (Remote File Transfer)

  • Purpose: Copy files between hosts over SSH.
  • Usage:
    • scp file user@hostname:/path/to/destination – Copy a file to a remote server.

File Transfer and Web Access

8. wget – Download Files from the Web

  • Purpose: Download files via HTTP, HTTPS, or FTP.
  • Usage:
    • wget http://example.com/file – Download a file from the web.

9. curl – Transfer Data with URLs

  • Purpose: Interact with web resources, download or send data.
  • Usage:
    • curl http://example.com – Fetch the content from a URL.

DNS Management

10. nslookup – Query DNS Servers

  • Purpose: Look up DNS records for a domain.
  • Usage:
    • nslookup example.com – Get DNS information for the domain.

Network Configuration & Monitoring

11. nmcli – NetworkManager Command-Line Interface

  • Purpose: Manage network connections.
  • Usage:
    nmcli device status  # Show status of all network devices
    nmcli connection show  # List all network connections
    nmcli device wifi list  # List available Wi-Fi networks

12. ss – Socket Stat

  • Purpose: Display socket connections (similar to netstat but faster).
  • Usage:
    ss -tuln  # Show listening TCP and UDP sockets
    ss -s  # Show summary of socket statistics

13. nmap – Network Exploration and Security Auditing Tool

  • Purpose: Scan and discover hosts/services on a network.
  • Usage:
    nmap 192.168.1.1  # Scan a single IP
    nmap -p 1-65535 192.168.1.1  # Scan all ports on an IP

14. tcpdump – Network Packet Analyzer

  • Purpose: Capture network traffic and analyze it.
  • Usage:
    sudo tcpdump -i eth0  # Capture traffic on eth0
    sudo tcpdump -i eth0 port 80  # Capture HTTP traffic
    sudo tcpdump -w capture.pcap  # Save captured traffic to file

15. ethtool – Network Interface Controller (NIC) Configuration

  • Purpose: Display or change network interface settings.
  • Usage:
    sudo ethtool eth0  # Display information about eth0
    sudo ethtool -s eth0 speed 1000 duplex full  # Set NIC speed to 1000 Mbps (full-duplex)

Network Routing & NAT

16. ip route – View or Modify Network Routing

  • Purpose: Manage and inspect routing tables.
  • Usage:
    ip route show  # Show routing table
    ip route add default via 192.168.1.1  # Set default gateway
    ip route del 192.168.1.0/24  # Delete a route

17. sysctl – View and Change Kernel Parameters at Runtime

  • Purpose: Modify kernel parameters (like network settings).
  • Usage:
    sysctl net.ipv4.ip_forward  # Check if IP forwarding is enabled
    sudo sysctl -w net.ipv4.ip_forward=1  # Enable IP forwarding

18. iptables for NAT (Network Address Translation)

  • Purpose: Set up port forwarding or NAT.
  • Usage:
    sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80  # Port forwarding

19. bridge – Network Bridge Configuration

  • Purpose: Create and manage network bridges.
  • Usage:
    sudo ip link add name br0 type bridge  # Create a bridge
    sudo ip link set dev eth0 master br0  # Add interface to bridge
    sudo ip link set dev br0 up  # Bring the bridge up

Related Articles