Stephen J Marks

"Do One Thing Well" - Doug Mcllroy

image

Hello! I’m a Computer Science and Math major with a deep passion for Linux, holding expertise as a Linux specialist. My enthusiasm extends beyond just using the system—I am a committed open source enthusiast, actively contributing to and learning from the community. I am currently seeking a position that allows me to leverage my skills in Linux, particularly in roles related to system administration and DevOps. My professional journey includes significant experience in IT at Managed Service Providers, where I’ve honed my technical and problem-solving skills. I’m also proud to hold certifications from CompTIA and RedHat, which underscore my commitment and expertise in the field. I am excited about the opportunities to bring my technical acumen and passion for Linux to a dynamic team, where I can contribute to meaningful projects and continue to grow in my career.
I want this site to not only be a place where I advertise myself, but can also be myself. So here anything relating to my interests will be found. When I’m not immersed in the digital world, I love stepping into nature. Camping and hiking are my go-to activities for recharging and reconnecting with the outdoors. I also love watching and analyzing films, or consuming material on math, science, or cooking.

Passions 🔥

  • Linux & Open Source 🐧
  • Films 🎥
  • Camping & Hiking 🌲
  • Mathematics 🧮
  • Cooking & Baking 🍳
  • Socializing 🗣️

Links

Resume 📄

Profile 🖋️

Dynamic system administrator and proficient coder, leveraging a broad knowledge base in technology with sharp programming skills. A dedicated, adaptable enthusiast passionate about advancing the field through open-source contributions.

Degrees and Certifications 🎓

Bachelor's of Computer Science

  • Institution: Cal State Bakersfield (In Progress)

Associate of Computer Science & Math

  • Institution: Bakersfield College
  • Year: 2023

Red Hat Linux Certified Administrator

  • Certifying Body: Red Hat
  • Year: 2023

CompTIA+ Certifications Itemized

  • Certifying Body: CompTIA+
  • Years: 2020 - 2022
  • Details:
    • Linux+
    • Network+
    • Security+

Employment 🛠️

Library STEM Programming Consultant

  • Employer: County of Kern
  • Years: 2023 - Current
  • Role: Spearheaded and executed educational programs, successfully engaging local youth in computer science, elevating their proficiency in STEM subjects.

IT Support Engineer & Administrator Level 2

  • Employer: LanPro Systems
  • Years: 2020 - 2022
  • Role: Administered Linux VoIP servers, resolved complex tickets, managed AD users, performed system backups, provisioned servers & workstations, and implemented scripts & automated tasks.

Peer Tutor

  • Institution: Bakersfield College
  • Years: 2019 - 2020
  • Role: Led peer instruction in key computer science areas; significantly improving classmates' understanding and performance in programming, logic, and binary arithmetic.

Tutor

  • Institutions: Bakersfield College; Tutoring Club; Freelance
  • Years: 2019 - Current
  • Role: Effectively tutored in computer science, math, and physics; elevating student achievements in college and K-12.

Contact 📞

Strengths 💪

  • Linux
  • Programming/Scripting
  • System/Server Administration
  • Automation (Ansible / K8s / etc)
  • Virtualization (KVM / VMware)
  • Orchestration (Docker / K8s)
  • Provisioning (Ansible / Terraform)
  • Integration (Jenkins / Git)
  • Text Editing (VIM / VS)

Languages 🌐

  • Shell: Fluent
  • C: Fluent
  • Python: Fluent
  • Rust: Basic
  • Powershell: Intermediate
  • SQL: Basic
  • Assembly (x86 / ARM / MIPS): Competent
  • AWK: Basic
  • HTML + Markdown / CSS: Fluent
  • Latex: Intermediate

Works

These are links to my "books" or other writings. My goal is to solidify my own knowledge base while sharing whatever I know with others. I'm majorly self taught and promote self-teaching. Everything here is perpetually in progress.

Steve's Blog

This will be a blog where I will dump anything I want. It will probably be mostly tech related. Specifically Linux and open source stuff. Thoughts, critiques, criticisms, guides, advice, projects, anything. However, there will probably be some life stuff here too. This will be fun. There will be typos.

Enjoy

On Installing Gentoo For Some Reason (2024-08-21)

gentoo

I decided to install Gentoo on a whim. I've done it a couple of times in the past, even on Raspberry Pis. But that was before the recent change implementing mass binary alternatives to the compilation Gentoo is known for. Binaries have been available for a while already, but I'm interested to check out this change. Gentoo's biggest con for me is the time it takes to install packages if you don't have a Threadipper. Here I will just be going over my thoughts and experiences. This isn't an actual guide, for that use their handbook for the appropriate architecture.

Where

I decided to install Gentoo in a vm. I went with virtualbox over kvm/qemu because a bridged network will already be setup for ssh and it will be easier to get a shared clipboard going.

Installation of Minimal Linux Distros

Minimal distros like Gentoo and Arch have the essential parts of every distribution, just less obfuscated. Their installation generally has the following cadence:

  • Partition drives and create filesystems
  • mount root partition
  • chroot into root partition
  • setup up install in chroot environment
    • network, packages, fstab, bootloader, users, etc.
  • post install Chroot is a command that essentially changes the root to a new location. So that everything within the chroot is happening relative to that new root. That is why we chroot into the mounted root partition during installs because at that point we are configuring the actual system to be installed. Take not of this command as it will ultimately help troubleshoot installs from a live cd. Often other paths have to be mounted from the host system to the chroot so that it can be a functioning live environment essentially.

Tips for Installing Gentoo

  • Remember to utilize chroot. You don't have to complete the install all at once. Per the handbook, past that point you can always mount your root partition into an environment and with the correct mounts and get back into the system. For there you can continue the installation or fix an issue.
  • If you are not installing Gentoo in a GUI already, and you have access to another machine on the network, I recommend remoting into the machine Gentoo is being installed on via SSH. This can be done after being chrooted. Copy and pasting from a web browser makes things so convenient. This will require network bridging
    1. Get network up: net-setup [interface]
    2. Change root's password via passwd
    3. Start the ssh daemon with: /etc/init.d/sshd start
  • Take advantage of the newly available binaries for better install times
  • Use ccache. At the very least. ccache is a program that caches compiled source so it doesn't have to be recompiled later. Makes later compilations quicker, which is needed on Gentoo.
  • Use distcc is you have other computers on the network with good CPUs. distcc distributes compilation workloads across multiple computers. Can make your install a breeze.

My Troubles

  • Forgot boot flag on /boot which I caught before it mattered
  • fstab typo which caused first boot to be to emergency.target

I fixed both by chrooting back into root and fixing the issue.

Gentoo is fun

I like Gentoo for messing around. It seems like a good educational tool the way LFS can be. Also seems great for development environments. Would never use it on an actual install for a server or desktop though...again. In those instances there is way too much upkeep for what is gained.

Major Packaging Systems Disambiguation 📦 (2024-08-21)

Package Formats

Package formats are the way that software data is organized for distribution prior to installation. Every major Linux branch will have a package format it utilizes. The two most major types are .deb and .rpm. They are found on Debian based distros and Red Hat based distros respectively. Package installers and managers exist for every format and there are typically several for each type that "wrap" or encapsulate another, and sometimes its even in a nested sense. They can be described as having levels such as: "low", "medium", and "high".

.deb

A .deb package is the package used for Debian based distributions. The most major ones being Debian itself and Ubuntu. Deb packages consist three ordered files. Two are tar archives that support compression. One for the metadata known as control information and another for the installable data. The third is a file containing the format version number.

.deb structure

  • The structure of a .deb package

dpkg

Dpkg is a low level packaging tool. It isn't a package manager because it doesn't actually manage the packages and dependencies. The dpkg command can be used to install and remove .deb files directly.

  • dpkg -i filename.deb installs a package
  • dpkg -l lists files that match a pattern
  • dpkg -S searches for a filename from installed packages
  • dpkg -r packagename removes an installed packages The packages dpkg and dpkg-dev contain the suit of utilities and development tools respectively.

apt-get and apt

Apt-get is a medium level package manager that utilizes dpkg. It can be thought of as a front-end for dpkg. Apt is a wrapper for apt-get that supports greater functionality such as: better dependency resolution, native search capabilities, and autoremoval of orphaned packages during upgrades. Apt is an amalgamation of the functionalities of separate utilities like apt-get and apt-cache. It is recommended that apt-get be reserved for automation. But for the most part apt and apt-get have the same sub-commands and functionality. Apt and Apt-get share the following:

  • apt update syncs the package indexes and sources
  • apt upgrade installs the current versions of packages
  • apt install installs individual or listed packages
  • apt clean clears cache of package files
  • apt autoclean only clears package files that can no longer be downloaded.

apt exclusive

apt search, apt show, apt policy, apt purge apt also has a set of sub-commands not found in apt-get such as:

  • apt search searches the list of packages for a regex term.
  • apt show outputs information on a given package

apt Frontends

The are graphical front ends for apt as well like the following:

.rpm

The counterpart to .deb in Red Hat based and upstream distros is the .rpm package format. The file has the naming convention: name-version-release-arch.rpm. This name is appended with -devel for libraries containing two separate packets for precompiled code and the headers. The package is usually provided in binary format and contains:

  • The lead, which identifies the file as an RPM file and contains some obsolete headers.
  • The signature, which can be used to ensure integrity and/or authenticity.
  • The header, which contains metadata including package name, version, architecture, file list, etc.
  • A file archive (the payload), which usually is in cpio format, compressed with gzip. The rpm2cpio tool enables retrieval of the cpio file without needing to install the RPM package.

rpm

rpm is the low level counterpart of dpkg for .rpm packages and its purpose and syntax is similar:

  • rpm -i packagename.rpm installs a package
  • rpm -U packagename.rpm upgrades a package
  • rpm -ivh package-file installs a package with verbose output and a progress bar
  • rpm -q query-options package searches for an installed package

YUM (Yellow Dog Updater, Modified)

Yellow Dog Updater or YUM is a medium level package manager for Red Hat based distros that acts as an rpm front-end. However, it has since been deprecated.

DNF (Dandified YUM)

Dandified YUM or DNF is the high level package manager that has replaced YUM has the current and up to date rpm front-end. The syntax is similar to apt.

DNF Command Reference

DNF (Dandified YUM) is the package manager for Fedora, CentOS, and RHEL distributions. Here is a list of commonly used commands:

  • Update Package Cache:

    dnf check-update
    
  • Upgrade All Packages:

    dnf upgrade
    
  • Upgrade Specific Package:

    dnf upgrade <package_name>
    
  • Install a Package:

    dnf install <package_name>
    
  • Remove a Package:

    dnf remove <package_name>
    
  • List Available Groups:

    dnf group list
    
  • Install a Package Group:

    dnf group install <group_name>
    
  • Remove a Package Group:

    dnf group remove <group_name>
    
  • Search for a Package:

    dnf search <keyword>
    
  • Display Information about a Package:

    dnf info <package_name>
    
  • Clean Cache:

    dnf clean all
    
  • Auto-remove Unneeded Packages:

    dnf autoremove
    
  • List Enabled Repositories:

    dnf repolist
    
  • Add a Repository:

    dnf config-manager --add-repo <repository_url>
    
  • Enable a Repository:

    dnf config-manager --set-enabled <repository_name>
    
  • Disable a Repository:

    dnf config-manager --set-disabled <repository_name>
    
    

Advanced Tips and Tricks

Advanced Tips for apt

  1. Full Upgrade vs Safe Upgrade:

    • apt full-upgrade performs upgrades that may also remove installed packages if that's necessary to upgrade the system as a whole.
    • apt upgrade will only upgrade packages without removing any packages.
  2. Holding Packages:

    • To prevent a package from being automatically updated, use sudo apt-mark hold package_name.
    • To allow it again, use sudo apt-mark unhold package_name.
  3. Searching Package Listings:

    • Use apt-cache search keyword to search for packages. It searches descriptions and names.
    • apt-cache pkgnames starts listing packages alphabetically.
  4. List All Versions of a Package Available for Installation:

    • Use apt list -a package_name to see all versions of a package available in your repositories.
  5. Using Snapshots:

    • If you want to return your packages to a previous state, you can use apt with snapshots from a backup tool like Timeshift.
  6. Automatic Removal of Unused Packages:

    • After uninstalling an application, use sudo apt autoremove to remove dependencies that were installed with applications and that are no longer used by anything else on the system.
  7. Find Which Package a File Belongs to:

    • Use apt-file search path/to/file to find out which package a particular file belongs to.

Advanced Tips for dnf

  1. History and Undo/Redo Operations:

    • dnf history lists transaction history. You can undo or redo transactions using dnf undo transaction_id or dnf redo transaction_id.
  2. Repository Management:

    • Enable or disable repositories on the fly with dnf config-manager --set-enabled repo_name or dnf config-manager --set-disabled repo_name.
  3. DNF Automatic:

    • Install dnf-automatic for automatic daily package updates. It can be configured to only download, download and install, or even send email notifications.
  4. List and Remove Orphaned Packages:

    • Use dnf list extras to list orphaned packages (packages not available from currently configured repositories).
    • Remove them with dnf remove $(dnf repoquery --extras --exclude='kernel*').
  5. Using DNF Plugins:

    • Enhance dnf's capabilities by installing plugins like dnf-plugin-system-upgrade for upgrading Fedora releases, or dnf-plugins-core for additional features like managing core repositories.
  6. Cache Management:

    • Use dnf clean dbcache to clean the cache to reduce disk space usage. dnf makecache to regenerate the cache improving the performance of future installations.
  7. Find if a Specific Package is Available:

    • Use dnf provides '*/filename' to find which packages provide a specific file.

On Inodes and the Inode Pointer Structure (2024-07-30)

Inodes are a fundamental part of the data structure that stores and references all data available on a storage device.

File Names Are References

The way files and directories are abstracted the end user typically thinks of files being nested. However, this isn't truly the case. Directories are simply lists of inode and file name pairs of the file names underneath, the name of the parent, and the name of itself. An inode is an entity that has a unique number and contains the file metadata, and pointers to the actual data the file "contains". That's it. Inodes do not store their "names" and all the filesystem really cares about are the inodes. File names are essentially just a human readable label mapped to an inode.

What Does An Inode Contain And Reference?

Inodes are where the file's metadata is stored. However, the data itself is not there. The data is referenced through a system of pointers also stored in the inode.

Typical Inode Pointer Structure

The typical pointer structure is implemented in ext* filesystems among others. It has the following qualities:

  • *inode pointer structure:
    • 12 direct pointers that directly point to blocks of the file's data
    • 1 singly indirect pointer (pointing to a block of direct pointers)
    • 1 doubly indirect pointer (pointing to a block of single indirect pointers)
    • 1 triply indirect pointer (pointing to a block of doubly indirect pointers)
    • fixed block size (increase redirection when required, data can be stored non contiguously
    • inodes assigned fixed amount at filesystem instantiation, amount of indirect blocks are not fixed
    • number of pointers dependent on block size and size of pointers The pointers are set up to use direct pointers and others with varying levels of indirection. This is so that the structure can support varying amounts of data while remaining static. If more space is needed, the system can simply use any unclaimed data block at some far off address through redirection.

Pointers and Metadata

Here is a diagram of the structure of inodes:

inodes

You can see the structure of the pointers that were previously discussed. However, the undiscussed metadata section is present as well. This section contains metadata such as filer permissions, ownership, edit history, etc. An exact list of metadata in an inode will be provided in the next subsection.

Viewing Contents of Inodes

The contents of inodes can be viewed using the stat system call.

stat test.txt
  File: test.txt
  Size: 15        	Blocks: 8          IO Block: 4096   regular file
Device: 259,2	Inode: 30158006    Links: 3
Access: (0644/-rw-r--r--)  Uid: ( 1001/   steve)   Gid: ( 1001/   steve)
Access: 2024-07-26 08:23:43.390310050 -0700
Modify: 2024-07-26 08:24:02.074309630 -0700
Change: 2024-07-28 13:29:14.971830641 -0700
 Birth: 2024-07-26 08:23:43.390310050 -0700

This command lists the contents of the inode test.txt is paired to. The metadata an inode contains includes:

  • File Type: Indicates the type of file (e.g., regular file, directory, symbolic link).
  • Permissions: Specifies read, write, and execute permissions for the owner, group, and others.
  • Owner User ID (UID): The user ID of the file's owner.
  • Owner Group ID (GID): The group ID of the file's owner group.
  • File Size: The size of the file in bytes.
  • Number of Hard Links: The count of hard links pointing to this inode.
  • Timestamps:
    • Access Time (atime): Last time the file was accessed.
    • Modification Time (mtime): Last time the file content was modified.
    • Change Time (ctime): Last time the inode metadata was changed.
  • File Size in Blocks: The number of blocks allocated to the file.
  • Extended Attributes: Additional metadata such as security labels or custom attributes.
  • Flags: File flags indicating special characteristics or behaviors (e.g., immutable, append-only).
  • Generation Number: A number that changes each time the inode is reused, used to detect stale file handles.
  • File System Identifier: An identifier for the file system where the inode resides.
  • The device ID of the file if it is a device file. Links are discussed in the next section.

File names are known as hard links. And the nature of the inode structure inherently allows files to have multiple hard links. the -i option on various commands outputs information on a file's inodes.

30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt

Here ls -li long lists with the inode number. So test.txt is mapped to inode 30158006. To create a hard link the command ln is used.

ln test.txt hard_link_to_test.txt

This command creates a hard link named hard_link_to_test.txt to test.txt.

ls -li test.txt hard_link_to_test.txt 
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 hard_link_to_test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt

Here we can see that these two files share the same inode number: 30158006. This means that both file names are mapped to that inode and thus are referencing the same data.

There is also the concept of a soft link aka a symbolic link. These links are file names that are pointers to other names. A soft link can be created with the -s option as in ln -s.

ln -s test.txt soft_link_to_test.txt

This command creates a soft link named soft_link_to_test.txt to test.txt.

ls -li test.txt hard_link_to_test.txt soft_link_to_test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 hard_link_to_test.txt
30157667 lrwxrwxrwx  8 steve 28 Jul 13:37 soft_link_to_test.txt -> test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt

Here we can see that the soft link does not share the inodes of the hard links but has its own. That is because it is pointing to the file name test.txt and not mapped to that filename's inode as a hard link would be. A soft link is mapped to its own inode, and that inode contains the path of the file being pointed to. To unlink a link the unlink command can be used.

 unlink hard_link_to_test.txt 
╭─steve@kathy-office ~/test
╰─❯ unlink soft_link_to_test.txt 
╭─steve@kathy-office ~/test
╰─❯ ls -li test.txt hard_link_to_test.txt soft_link_to_test.txt
"hard_link_to_test.txt": No such file or directory (os error 2)
"soft_link_to_test.txt": No such file or directory (os error 2)
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt

I've seen hard links described as a "poor man's backup" which means that if one filename is deleted the inode isn't inaccessible. There is still some other name mapped to that inode. When a file is deleted via something like rm, the data still exists. This will be covered in a later section. This also saves space, if what is hard linked in large, but needs to exists in multiple paths. And since inodes store metadata such as permissions and file attributes, the hard link will share them as well.

Soft links allow for having files accessible from multiple paths without moving or copying anything. Another use is version management. Say there is one service or script that runs and depends on something having a certain path or name. but it changes regularly. A soft link to it won't. So instead of rewriting anything, the soft link can just be redirected. Soft links also have the capability of linking to files across filesystems and devices, where hard links can't.

Restrictions

Linking has some limitations due to the inherent structure of filesystems and inodes.

Linking To Directories

Directories can not be hard linked in Linux. Historically this has been possible, but most operating systems disable this behavior now to avoid cycles. A notable counterexample is that a superuser can make hard links to directories in MacOS 10.5. Directories can be soft linked because a soft link's inode just contains the path of the file being pointed to.

Inode Exhaustion

Filesystems have a limited and fixed number of inodes for use, and all data stored needs an inode pointing to it. If one created countless small files containing nothing each would require an inode and they would eventually run out, and no more files can be created. This is known as inode exhaustion. And since the files were empty there wold still be ample free space, and everything would appear fine on the surface. The number of available inodes can be checked using df -i.

df -i
Filesystem     Inodes IUsed IFree IUse% Mounted on
udev             1.7M   535  1.7M    1% /dev
tmpfs            1.7M   936  1.7M    1% /run
/dev/nvme0n1p2    58M  606K   57M    2% /
tmpfs            1.7M   712  1.7M    1% /dev/shm
tmpfs            1.7M     6  1.7M    1% /run/lock
tmpfs            1.7M    94  1.7M    1% /tmp
/dev/nvme0n1p1      0     0     0     - /boot/efi
tmpfs            348K   106  348K    1% /run/user/1001

Based on this output we can see I have plenty of inodes free.

Setting Number of Inodes in Filesystem

Since the amount of inodes are fixed the only way to alter it is to set it at filesystem creation. Say we are creating an ext4 filesystem. The mkfs.ext4 can do this. The following is from its man page: >-N number-of-inodes Overrides the default calculation of the number of inodes that should be reserved for the file system (which is based on the number of blocks and the bytes-per-inode ratio). This allows the user to specify the number of desired inodes directly.

Note that there are some exceptions. For instance Btrfs is capable of dynamically allocating inodes so the amount is not fixed.

Alternative Structures and Filesystems

Many filesystems exist that are fundamentally different that something like ext*. They do not use inodes but utilize other data structures such as B-trees. The following is a list of filesystems that do not use inodes:

  • FAT (File Allocation Table): Used by MS-DOS and early versions of Windows, FAT file systems, including FAT12, FAT16, and FAT32, use a file allocation table to manage files rather than inodes.
  • exFAT (Extended File Allocation Table): Designed by Microsoft to replace FAT32, exFAT is optimized for flash drives and does not use inodes.
  • ReFS (Resilient File System): Developed by Microsoft, ReFS uses B-trees for metadata storage and does not use inodes.
  • HFS (Hierarchical File System): Used in older Apple Macintosh systems, HFS uses a catalog file and extents overflow file for metadata instead of inodes.
  • HFS+ (Hierarchical File System Plus): An updated version of HFS used in macOS before APFS, HFS+ uses B-trees for metadata storage, avoiding the inode structure.
  • APFS (Apple File System): The current file system for macOS and iOS, APFS uses container and volume structures with object identifiers instead of inodes.
  • NTFS (New Technology File System): Used by modern versions of Windows, NTFS uses a Master File Table (MFT) to store metadata rather than inodes.
  • IBM GPFS (General Parallel File System): Now known as Spectrum Scale, GPFS uses a distributed metadata model with descriptors rather than traditional inodes.

Retrieving Unclaimed Data

Recall that when a hard link is deleted via rm the data still exists, however once the last hard link to the inode is gone the metadata is deleted and there is no way to access the data. The data still exists but the space it occupies is now unclaimed can be reclaimed and overwritten by new data. If data needs to be recovered cease all writes immediately. Either unmount the drive or boot into a live environment. The drive can not be written to until the data is located. There are a number of programs that can inspect data fields for information indicating the types of data stored there. They may utilize a technique of data recovery known as file carving in which data is reconstituted from fragments.

In conclusion, understanding inodes is a critical part of understanding linking and the filesystems used on Linux.


Resources

Inode Pointer Structure

Inodes

Inodes

Linking

Unix File System

On Pseudo Devices (2024-07-30)

One of the most interesting and powerful design philosophies behind Unix and its kin is the notion of everything being a file. Everything. For instance the kernel state is is abstracted as files in /proc, and access to data in physical devices is abstracted as files in /dev. Files is /dev are known as special files. There is a kind of special file called pseudo devices. These kinds of files don't necessarily abstract access to physical devices, but abstract data and its manipulation as files. I find this concept incredibly fascinating and is one of the reasons I love using and learning Linux. This post will be on pseudo devices - what they are, why they exist, and how they are and can be used.

Available Pseudo devices in Linux

Pseudo devices can be found in /dev. Here is a list of all the pseudo devices available in Linux:

  • /dev/null - A special file that discards all data written to it and provides zero bytes when read.
  • /dev/zero - Provides a continuous stream of null (zero value) bytes.
  • /dev/random - Provides random data generated from environmental noise.
  • /dev/urandom - Similar to /dev/random but uses a pseudo-random number generator to provide data.
  • /dev/full - Always returns an error indicating that the device is full when writing to it.
  • /dev/ptmx - Used to create a new pseudo-terminal master and slave pair.
  • /dev/tty - Represents the controlling terminal for the current process.
  • /dev/console - Represents the system console.
  • /dev/loopX - Loopback devices that allow a file to be mounted as a filesystem.
  • /dev/ppp - Represents a point-to-point protocol network device.
  • /dev/ttyS* or /dev/ttyUSB* or /dev/ttyACM* - Serial devices.
  • /dev/net/tun and /dev/net/tap - Network tunnel devices for tunneling IP traffic (TUN) and Ethernet frames (TAP).
  • /dev/fuse - Filesystem in Userspace, allows non-privileged users to create their own filesystem without modifying kernel code.
  • /dev/shm - Represents a temporary filesystem for shared memory.
  • /dev/mem - Provides access to the physical memory of the system.
  • /dev/kmsg - Used for logging kernel messages.
  • /dev/bus/usb - Represents USB devices and buses.
  • /dev/disk/by-id - Symbolic links to storage devices based on their IDs.
  • /dev/disk/by-path - Symbolic links to storage devices based on their physical paths.
  • /dev/input/event* and /dev/input/mice - Represents input devices like keyboards, mice, and other human interface devices.

Most of these devices serve the system, however there are pseudo devices available that can provide certain functionalities in the cli and scripts.

Data Manipulation

/dev/null/ can be used as a trash can basically. Any data you don't need can be streamed to this device as if you're chucking it into a black hole never to be see again. It's most often sued as a place to redirect either stdout or stderr in scripts or one-liners.

# Run the command in the background and discard its output
command > /dev/null 2>&1 &

dev/zero...outputs a stream of zeroes. This is often used for wiping out a file or drive. Here is a line that does this by writing to a file, and once the drive is full, the file is deleted.

        dd if=/dev/zero of=zeros; rm zeros

This can be part of a larger script used for backing up drives.

#Fill up the blank space on drive with zeros first (optional):

        dd if=/dev/zero of=zeros; rm zeros

#Recommended: Unmount drive before backing it up.

#Creating the archive:

        dd if=/dev/sda1 conv=noerror | gzip -c > sda1.img.gz

#Extracting the archive:

        cat sda1.img.gz | gzip -dc | dd of=/dev/sda1 conv=noerror

#Storing disk info:

        fdisk /dev/sda -l > sda1.txt

Random Data Generation

/dev/random or dev/urandom generates a random stream of data. This data can be dumped to overwrite drives with random data, or generate very strong passwords. Note that the c functions random(), srandom(), and the system call getrandom() are also at your disposal.

#!/bin/bash

# Generate the password
PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c "$1")

echo "Generated password: $PASSWORD"

This small script generates a random password of a length given as a command line argument.

#!/bin/bash

# Check if the user provided a drive as an argument
if [ $# -eq 0 ]; then
    echo "Usage: $0 /dev/sdX"
    echo "Example: $0 /dev/sda"
    exit 1
fi

# Drive to overwrite
DRIVE=$1

# Confirm with the user before proceeding
read -p "WARNING: This will irreversibly overwrite all data on $DRIVE. Are you sure? (yes/no): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
    echo "Operation cancelled."
    exit 1
fi

# Overwrite the drive with random data
echo "Overwriting $DRIVE with random data. This may take a while..."
dd if=/dev/urandom of=$DRIVE bs=1M status=progress

echo "Overwrite complete."

This one overwrites a drive with random data.

Always take advantage of pseudo devices, especially /dev/null in scripts and the cli. There are other pseudo devices we use on Linux such as pseudoterminals, serial devices, and even pipes themselves are considered pseudo devices. I recommend reading up on these as well.


Device Files

/dev/random

Bootloaderless Boot With EFIstub (2024-07-25)

The most prevalent bootloader on Linux is GRUB2, but there are other offerings put there such as LIFO. But did you know that...you don't need a bootloader at all?

UEFI

UEFI, the replacement of the legacy BIOS, is actually capable of selecting and loading kernels directly, which I don't see many people doing. You don't actually need a booatloader with UEFI. The downside is that if you would like to boot other OSs, you'll have to access the UEFI every time you would like to boot something else. But if you only have a single OS installed, I don't see any downsides.

EFIstub

This can be achieved with an EFIstub. An EFIstub is essentially a kernel that is executable by EFI. This may already be built into the kernel you're using if CONFIG_EFI_STUB=y is set. If not... well compiling the kernel will be its own post. The UEFI essentially just needs an entry for the kernel that is being booted. You could do this form withing your UEFI's shell, but I use efibootmgr for this. It can manage UEFI boo entries from within Linux. If the UEFI is configured appropriately and its version supports it, booting the kernel shouldn't be an issue. Note that keeping the kernel that is being booted updated automatically is distro specific so refer to your distro's documentation. Arch's states:

pacman will directly update the kernel that the EFI firmware will read if you mount the ESP to /boot.

So that's what I did.

efibootmgr

Setting the UEFI boot entry is jsut a single command. I wrote a small script that can be used to automate the process. The script sets it up using the UUID of the root partition. It creates an entry and deletes the previous one if it already exists.

#!/bin/sh

# Delete the existing boot entry
efibootmgr -b 0 -B > /dev/null
printf "Deleted boot entry: 0000\n\n"

# Retrieve the UUID for the root partition
ROOT_UUID=$(sudo blkid | grep root | awk -F 'UUID="' '{split($2, a, "\""); print a[1]}')

# Reload the entry with the new UUID
printf "Reloaded entry 0000...\n"
efibootmgr --disk /dev/nvme0n1 --part 1 --create --label "Arch Linux" --loader /vmlinuz-linux --unicode "root=UUID=$ROOT_UUID rw initrd=\initramfs-linux.img rd.driver.blacklist=nouveau nvidia-drm.modeset=1" --verbose --timeout 0 | grep "Boot0000"

After this I select my kernel in the UEFI boot config and I'm good to go. If you use this script remember to use your own kernel boot parameters if you need them and to use the path to the correct disk. In my case its /dev/nvme0n1.

You should have a fast boot and a good time.

Built-ins, Utilities, Functions, and System Calls Disambiguation (2024-07-25)

The differences between these haven't always been clear to me in the context of Linux. Many shared names also caused me some confusion. I'm assuming this is the case for others and an explanation may serve them.

Core Utilities

Core utilities or coreutils are just sets of programs commonly installed on systems by default. The most common and ubiquitous set of coreutils are are the GNU coreutils. If you're on Linux, you're probably using them. The coreutils are discrete binaries that can each be ran for basic and essential functionality required to use a system. For example, ls and mv are coreutils. There are alternative sets of coreutils such as uutils, which are the gnu ones rewritten in Rust. There is also Busybox which are coreutils reimplemented as a single binary. Busybox is usually found on distributions of Linux like Alpine that are extremely small intended for embedded environments. And other operating systems have their equivalents such as the BSDs. In fact there are some that I personally prefer over gnu counterparts such as doas.

Shell Built-ins

The first bit of confusion arises with the introduction of shell built-ins. A shell being an environment used to interact with the components and indirectly the kernel of the operating system; a built-in is a command that is in the shell itself. It is not its own program or binary and does not exist anywhere on the system. The which command can tell you if a command is built-in or not. which outputs the path of executable files, so if you run a command as an argument and a path isn't output, its built-in.
The printf command is a case where there is likely both a binary installed and a shell built-in (at least in the case of bash). To force the use of the binary one would just run the path to it. For example:

 /usr/bin/printf "Hello World!\n"
Hello World!

To force the use of the built-in the command builtin (which funnily enough is itself built-in) can be ran with the desired built-in command as an argument. For example:

builtin printf "Hello World!\n"
Hello World!

By default the binary is used.

C Functions

You may have noticed that printf shares the name of the c standard function c printf(). At the end of the day almost everything in Linux is ultimately C and the printf command is a kind of wrapper that just invokes the c function to output and format text. glibc is the gnu implementation of the c standard library which is, like the coreutils, on the vast majority of Linux distributions.

System Calls

Like commands that share the names of c functions, they can also share the names of system calls. System calls a c function that utilizes the kernel API to interface with the kernel. There exists c wrapper functions for system calls invoke the system call. Let's use the wait command as an example going down the layers of abstraction from top to bottom.

wait Built-in

The wait command is a built-in that detects changes in the status of a process.

$ sleep 10 &
$ jobs -l
[1] + 18057 Running              sleep 10
$ wait 18057
[1] + Done                       sleep 10
$

wait terminates once the job ends.

wait C Function

The wait() function in the c standard library is what the wait built-in is effectively wrapping.

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    pid_t pid = fork();

    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // Child process
        printf("Child process is running\n");
        sleep(1);  // Simulate some work with sleep
        exit(EXIT_SUCCESS);
    } else {
        // Parent process
        wait(NULL);  // Wait for the child to terminate
        printf("Child process has terminated\n");
    }

    return 0;
}

The above program contains fork() and wait(), two c functions that wrap system calls. This code demonstrates the use of wait() as a c function.

wait System Call

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>

int main() {
    pid_t pid = fork();

    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // Child process
        printf("Child process is running\n");
        sleep(1);  // Simulate some work with sleep
        exit(0);
    } else {
        // Parent process
        syscall(SYS_wait4, -1, NULL, 0, NULL);  // Wait for the child to terminate
        printf("Child process has terminated\n");
    }

    return 0;
}

The above code utilizes syscall() which is a function that accepts system calls themselves as parameters. SYS_wait is the actual system call. And all system calls share the same naming scheme.

System Calls All The Way Down

So every command - whether it be a binary or built-in - issued is ultimately some c code and a system call. And many share the same name! So when you're reading some documentation or a man page, understand the distinctions between them, or how there all parts of a greater whole at times abstracting one another. Then there is no need to be confused.


Some System Calls

  • SYS_read: Read from a file descriptor.
  • SYS_write: Write to a file descriptor.
  • SYS_open: Open a file.
  • SYS_close: Close a file descriptor.
  • SYS_stat: Get file status.
  • SYS_fstat: Get file status of an open file.
  • SYS_lstat: Get file status of a symbolic link.
  • SYS_poll: Wait for some event on a file descriptor.
  • SYS_lseek: Reposition read/write file offset.
  • SYS_mmap: Map files or devices into memory.
  • SYS_mprotect: Set protection on a region of memory.
  • SYS_munmap: Unmap a region of memory.
  • SYS_brk: Change data segment size.
  • SYS_rt_sigaction: Examine and change a signal action.
  • SYS_rt_sigprocmask: Examine and change blocked signals.
  • SYS_ioctl: Control device.
  • SYS_pread64: Read from a file descriptor at a given offset.
  • SYS_pwrite64: Write to a file descriptor at a given offset.
  • SYS_readv: Read data into multiple buffers.
  • SYS_writev: Write data from multiple buffers.
  • SYS_access: Check user's permissions for a file.
  • SYS_pipe: Create a pipe.
  • SYS_select: Synchronously monitor multiple file descriptors.
  • SYS_sched_yield: Yield the processor.
  • SYS_mremap: Remap a virtual memory address.
  • SYS_msync: Synchronize a file with a memory map.
  • SYS_mincore: Determine whether pages are resident in memory.
  • SYS_madvise: Give advice about use of memory.
  • SYS_shmget: Get a System V shared memory segment.
  • SYS_shmat: Attach a System V shared memory segment.
  • SYS_shmctl: Control operations on a shared memory segment.
  • SYS_dup: Duplicate a file descriptor.
  • SYS_dup2: Duplicate a file descriptor to a given descriptor.
  • SYS_pause: Wait for a signal.
  • SYS_nanosleep: High-resolution sleep.
  • SYS_getitimer: Get the value of an interval timer.
  • SYS_alarm: Set an alarm clock for delivery of a signal.
  • SYS_setitimer: Set the value of an interval timer.
  • SYS_getpid: Get process ID.
  • SYS_sendfile: Transfer data between file descriptors.
  • SYS_socket: Create an endpoint for communication.
  • SYS_connect: Initiate a connection on a socket.
  • SYS_accept: Accept a connection on a socket.
  • SYS_sendto: Send a message on a socket.
  • SYS_recvfrom: Receive a message from a socket.
  • SYS_sendmsg: Send a message on a socket.
  • SYS_recvmsg: Receive a message from a socket.
  • SYS_shutdown: Shut down part of a full-duplex connection.
  • SYS_bind: Bind a name to a socket.
  • SYS_listen: Listen for connections on a socket.
  • SYS_getsockname: Get socket name.
  • SYS_getpeername: Get name of connected peer socket.
  • SYS_socketpair: Create a pair of connected sockets.
  • SYS_setsockopt: Set options on sockets.
  • SYS_getsockopt: Get options on sockets.
  • SYS_clone: Create a child process.
  • SYS_fork: Create a child process.
  • SYS_vfork: Create a child process and block parent.
  • SYS_execve: Execute program.
  • SYS_exit: Terminate the calling process.
  • SYS_wait4: Wait for process to change state.
  • SYS_kill: Send a signal to a process.
  • SYS_uname: Get system information.
  • SYS_semget: Get a System V semaphore set.
  • SYS_semop: Operate on a System V semaphore set.
  • SYS_semctl: Control a System V semaphore set.
  • SYS_shmdt: Detach a System V shared memory segment.
  • SYS_msgget: Get a System V message queue.
  • SYS_msgsnd: Send a message to a System V message queue.
  • SYS_msgrcv: Receive a message from a System V message queue.
  • SYS_msgctl: Control operations on a System V message queue.
  • SYS_fcntl: Manipulate file descriptor.
  • SYS_flock: Apply or remove an advisory lock on an open file.
  • SYS_fsync: Synchronize a file's in-core state with storage device.
  • SYS_fdatasync: Synchronize a file's in-core state with storage device.
  • SYS_truncate: Truncate a file to a specified length.
  • SYS_ftruncate: Truncate an open file to a specified length.
  • SYS_getdents: Get directory entries.
  • SYS_getcwd: Get current working directory.
  • SYS_chdir: Change working directory.
  • SYS_fchdir: Change working directory of the calling process.
  • SYS_rename: Change the name or location of a file.
  • SYS_mkdir: Create a directory.
  • SYS_rmdir: Remove a directory.
  • SYS_creat: Create a file.
  • SYS_link: Create a new name for a file.
  • SYS_unlink: Delete a name and possibly the file it refers to.
  • SYS_symlink: Create a symbolic link.
  • SYS_readlink: Read value of a symbolic link.
  • SYS_chmod: Change permissions of a file.
  • SYS_fchmod: Change permissions of an open file.
  • SYS_chown: Change ownership of a file.
  • SYS_fchown: Change ownership of an open file.
  • SYS_lchown: Change ownership of a file, not following symbolic links.
  • SYS_umask: Set file mode creation mask.
  • SYS_gettimeofday: Get time.
  • SYS_getrlimit: Get resource limits.
  • SYS_getrusage: Get resource usage.
  • SYS_sysinfo: Get system information.
  • SYS_times: Get process times.
  • SYS_ptrace: Trace a process.
  • SYS_syslog: Read and/or clear kernel message ring buffer; set console_loglevel.
  • SYS_setuid: Set user identity.
  • SYS_setgid: Set group identity.
  • SYS_setpgid: Set process group ID.
  • SYS_getppid: Get parent process ID.
  • SYS_getpgrp: Get process group ID.
  • SYS_setsid: Create a session and set process group ID.
  • SYS_setreuid: Set real and effective user IDs.
  • SYS_setregid: Set real and effective group IDs.
  • SYS_getgroups: Get list of supplementary group IDs.
  • SYS_setgroups: Set list of supplementary group IDs.
  • SYS_setresuid: Set real, effective, and saved user IDs.
  • SYS_getresuid: Get real, effective, and saved user IDs.
  • SYS_setresgid: Set real, effective, and saved group IDs.
  • SYS_getresgid: Get real, effective, and saved group IDs.
  • SYS_getpgid: Get process group ID.
  • SYS_setfsuid: Set user ID used for filesystem checks.
  • SYS_setfsgid: Set group ID used for filesystem checks.

gnu++ in Rust (2024-07-24)

I've discussed rewrites of commonly used gnu utilites in Rust. I've written a script that installs cargo and every Rust rewrite with it. The script also optionally writes alias definitions to the appropriate shell rc file. It assumes bash by default. The script source will be pasted below, and the repo is on my Github.

Source

#!/bin/bash

# Default list of crates
default_crates=(
    "bat"
    "choose"
    "exa"
    "lsd"
    "git-delta"
    "du-dust"
    "duf"
    "broot"
    "fd-find"
    "ripgrep"
    "sd"
    "bottom"
    "gping"
    "procs"
    "zoxide"
    "dns-doge"
    "mcfly"
    "xh"
    "hyperfine"
)

# Default shell config file
shell_config=".bashrc"

# Usage function
usage() {
    echo "Usage: $0 [-a] [-s SHELL_CONFIG] [-f PACKAGE_FILE] [-h]"
    echo "  -s: Specify shell configuration file (.bashrc or .zshrc)"
    echo "  -f: Specify a file with a list of packages"
    echo "  -h: Display this help message"
    exit 1
}

flag=0
# Parse command-line options
while getopts ":as:f:h" opt; do
    case $opt in
        a)
            flag=1
            ;;
        s)
            shell_config="$OPTARG"
            ;;
        f)
            package_file="$OPTARG"
            ;;
        h)
            usage
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            usage
            ;;
    esac
done

# Read packages from file if specified
if [ -n "$package_file" ]; then
    if [ -f "$package_file" ]; then
        mapfile -t default_crates < "$package_file"
    else
        echo "Error: Package file not found: $package_file"
        exit 1
    fi
fi

install_rust() {
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  PATH="$HOME/.cargo/bin:$PATH"
  printf "\n" >> "$HOME/$shell_config"
  echo "export PATH=$PATH" >> "$HOME/$shell_config"
}

# Function to set up aliases
setup_aliases() {
    {
        printf "\n"
        echo "#gnu++ Rust Alternative Aliases"
        echo "alias cat='bat --paging=always'"
        echo "alias ls='exa -la'"
        echo "alias diff='git-delta'"
        echo "alias du='du-dust'"
        echo "alias df='duf'"
        echo "alias tree='broot'"
        echo "alias find='fd'"
        echo "alias grep='rg'"
        echo "alias find='fd'"
        echo "alias cut='choose'"
        echo "alias sed='sd'"
        echo "alias top='btm'"
        echo "alias ps='procs'"
        echo "alias cd='z'"
        echo 'eval "$(zoxide init bash)"'
        echo "alias dig='doge'"
    } >> "$HOME/$shell_config"
    echo "Aliases added to $HOME/$shell_config"
}

# Install packages and set up aliases
install_rust_crates() {
    for package in "${default_crates[@]}"; do
        cargo install --locked "$package"
    done
}

main() {
install_rust
install_rust_crates
if [ "$flag" -eq 1 ]; then
  setup_aliases
fi
echo "Installation complete."
}

main

Usage

Usage: ./gnu++.bash [-a] [-s SHELL_CONFIG] [-f PACKAGE_FILE] [-h]
  -s: Specify shell configuration file (.bashrc or .zshrc)
  -f: Specify a file with a list of packages
  -h: Display this help message

What I Use 🐧 (2024-07-23)

I realized I've yet to discuss what it is I use day to day in terms of Linux. This is a quick post dedicated to my setup.

Desktops/Laptops

On the desktop and I use Arch Linux. Arch is a rolling release distribution which means packages, including the kernel, are the latest available versions... which can lead to some issues. I've had small issues over the years using it mostly relating to dependencies breaking on updates. Usually manually holding back a package in /etc/pacman.conf fixes these issues. Random issues like some files not being deleted properly by the package manager preventing an update also arise but usually the issue can be manually fixed by reading an error message and investigating. All that being said the nature of Arch means that package availability is incredible. Not to mention the aur or Arch User Repository which is a repo consisting of packages packaged by users and developers themselves. While these may be inherently less trustworthy than official packages, I've almost never run into a situation where what I as looking for wasn't available on Arch.

Window Manager

My previously favorite window manager was dwm. I liked dwm but the philosophy involving manually patching source is very tedious and arbitrary. It seemed like core functionality was missing by default. So I decided to switch to hyprland because I wanted to switch to Wayland as my display server...protocol. Hyprland is technically a compositor that manages windows. Wayland has been amazing for me. Beforehand I was plagued by screen tearing on Xorg. However, I had to get an AMD gpu for my desktop for Wayland compatibility, but I needed to upgrade that anyway. Hyprland is amazing too. It is fast, clean, and offers amazing functionality. Very cool animations, great defaults, and the config file is easy to read and edit.

Servers

For server I either use Debian, Rocky Linux, or PiOS if I'm running things off of a Pi.

Dotfiles

My dotfiles are available on my Github.

Raspberry Pi at Home 🥧 (2024-07-22)

Let's Take a Trip To Pie Country

What is an SBC?

A SBC or single board computer is a computer...on a single board. All the components, CPU, RAM, flash, i/o, on a single PCB or printed circuit board. They're usually really small and relatively inexpensive. They're commonly used for small hobbyist projects because they often have buses one can just shove raw wires into, they're small enough to cram into whatever you want, and have relatively low power usages. They are commonly associated with edge computing and IoT or internet of things. These are two interrelated concepts involving smart fridges and toasters. Thermostats, air quality sensors, and home security systems. Washers and dryers. Even soldering irons and your girlfriend's hair iron. Devices containing tiny computers connected to the internet, sometimes storing information and doing computations on a user's local infrastructure.

Buying Options

There are many brands to choose from:

ManufacturerFlagship BoardProcessorArchitectureRAM OptionsStorage OptionsConnectivityPrice Range
Raspberry PiRaspberry Pi 5Broadcom BCM2712ARM Cortex-A764GB, 8GBmicroSD, USB 3.0Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet$60 - $80
ASUSTinker Board 2SRockchip RK3399ARM Cortex-A72/A532GB, 4GB16GB eMMC, microSDWi-Fi 5, Bluetooth 4.2, Gigabit Ethernet$85 - $100
NVIDIAJetson Nano 2GBNVIDIA Maxwell GPUARM Cortex-A572GBmicroSDWi-Fi (with USB adapter), Bluetooth (with USB)$59
ODROIDODROID-N2+Amlogic S922XARM Cortex-A73/A532GB, 4GBmicroSD, eMMCGigabit Ethernet, Wi-Fi (with adapter), Bluetooth$79 - $90
Rock PiRock Pi 4C+Rockchip RK3399ARM Cortex-A72/A534GBmicroSD, eMMCWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet$69.99
Banana PiBanana Pi M5Amlogic S905X3ARM Cortex-A554GBmicroSD, eMMCWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet$64 - $75
Pine64Pine A64+Allwinner A64ARM Cortex-A532GB, 4GBmicroSDWi-Fi (with USB adapter), Bluetooth (with USB)$29.99 - $39.99
BeagleBoardBeagleBone AI-64TI AM5729ARM Cortex-A154GBmicroSD, eMMCWi-Fi, Bluetooth, Gigabit Ethernet$100 - $125
UDOOUDOO Bolt V8AMD Ryzen V1605Bx86-648GB, 16GBM.2 NVMe, SATAWi-Fi, Bluetooth, Gigabit Ethernet$389 - $409
KhadasKhadas VIM3 ProAmlogic A311DARM Cortex-A73/A534GBeMMC, microSDWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet$139.99
Libre ComputerAML-S905X-CC (Le Potato)Amlogic S905XARM Cortex-A531GB, 2GB, 4GBmicroSDWi-Fi (with USB adapter), Bluetooth (with USB)$35 - $55
FriendlyARMNanoPi M4V2Rockchip RK3399ARM Cortex-A72/A532GB, 4GBmicroSD, eMMCWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet$65 - $75
RadxaRock Pi 3 Model ARockchip RK3588ARM Cortex-A76/A552GB, 4GB, 8GBeMMC, microSDWi-Fi 6, Bluetooth 5.0, Gigabit Ethernet$99 - $150
Orange PiOrange Pi 5BRockchip RK3588SARM Cortex-A76/A554GB, 8GB, 16GBeMMC, microSDWi-Fi 6, Bluetooth 5.0, Gigabit Ethernet$89 - $129

However, the market is dominated by the Raspberry Pi. It is the de facto option and is synonymous with the term SBC. There are a number of models to choose from:

ModelRelease DateProcessorArchitectureRAM OptionsStorage OptionsConnectivityPrice Range
Raspberry Pi Model B2012Broadcom BCM2835ARM11256MBSD Card100 Mbps Ethernet, 2x USB 2.0$25 - $35
Raspberry Pi Model A2013Broadcom BCM2835ARM11256MB, 512MBSD Card1x USB 2.0$20 - $25
Raspberry Pi Model B+2014Broadcom BCM2835ARM11512MBmicroSD100 Mbps Ethernet, 4x USB 2.0$25 - $35
Raspberry Pi Model A+2014Broadcom BCM2835ARM11256MB, 512MBmicroSD1x USB 2.0$20 - $25
Raspberry Pi 2 Model B2015Broadcom BCM2836ARM Cortex-A71GBmicroSD100 Mbps Ethernet, 4x USB 2.0$35
Raspberry Pi Zero2015Broadcom BCM2835ARM11512MBmicroSD1x mini HDMI, 1x micro USB$5
Raspberry Pi 3 Model B2016Broadcom BCM2837ARM Cortex-A531GBmicroSDWi-Fi 4, Bluetooth 4.1, 100 Mbps Ethernet, 4x USB 2.0$35
Raspberry Pi Zero W2017Broadcom BCM2835ARM11512MBmicroSDWi-Fi 4, Bluetooth 4.1, 1x mini HDMI, 1x micro USB$10
Raspberry Pi 3 Model A+2018Broadcom BCM2837B0ARM Cortex-A53512MBmicroSDWi-Fi 4, Bluetooth 4.2, 1x USB 2.0$25
Raspberry Pi 3 Model B+2018Broadcom BCM2837B0ARM Cortex-A531GBmicroSDWi-Fi 4, Bluetooth 4.2, Gigabit Ethernet (300 Mbps), 4x USB 2.0$35
Raspberry Pi 4 Model B2019Broadcom BCM2711ARM Cortex-A721GB, 2GB, 4GB, 8GBmicroSDWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 2x USB 3.0, 2x USB 2.0$35 - $75
Raspberry Pi 4002020Broadcom BCM2711ARM Cortex-A724GBmicroSDWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 3x USB 3.0, 1x USB 2.0$70
Raspberry Pi Pico2021RP2040ARM Cortex-M0+264KB SRAM2MB Flash26x GPIO, 2x SPI, 2x I2C, 2x UART, 3x ADC$4
Raspberry Pi Pico W2022RP2040ARM Cortex-M0+264KB SRAM2MB FlashWi-Fi 4, 26x GPIO, 2x SPI, 2x I2C, 2x UART, 3x ADC$6
Raspberry Pi 4 Model A2022Broadcom BCM2711ARM Cortex-A722GBmicroSDWi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 1x USB 3.0, 1x USB 2.0$25
Raspberry Pi Zero 2 W2021Broadcom BCM2710A1ARM Cortex-A53512MBmicroSDWi-Fi 4, Bluetooth 4.2, 1x mini HDMI, 1x micro USB$15
Raspberry Pi 52023Broadcom BCM2712ARM Cortex-A764GB, 8GBmicroSD, USB 3.0Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet, 2x USB 3.0, 2x USB 2.0$60 - $80

Why Raspberry Pi?

It being the de facto option it has the most support. The Pi project has: a Linux distribution, hardware /software support, devices such as sensors and monitors, and forums. And the massive slice of the market Pi has means third party support is substantial as well. There are countless add on boards or HATs and enclosures that can be had. No matter the fact that competing SBCs may have comparable or even surpassing performance capabilities, many will choose Raspberry Pi due the overwhelming support. The greatest con is the availability. Raspberry Pis have historically been extremely difficult to come by. Especially considering memory shortages, and global pandemic, and a chip shortage over the last few years, the 4th model was essentially impossible to get, especially at retail. There are entire databases dedicated to tracking retailer stocks. However, the release of the 5th model placated most and made obtaining at a reasonable price possible.

What I Use Them For

Again there are a plethora of way to utilize a Pi due to the sheer amount of openness and attachable boards and devices. I personally use them in my homelab. I use them to host a variety of services, usually through containerization such as Docker. My Raspberry Pi 4s and 5s serve:

pi box

A freshly arrived piKVM

That piKVM running booted off of a USB

I've used containers to run things like this as often as possible. Many utilities are available as container images on Dockerhub, however mileage may vary as ARM image are less common. I prefer containers due to the contained nature of the binaries and configurations. Everything can be contained in a single docker-compose file, which is very convenient. In the past I've even had my Pis clustered using Kubernetes, but that was more for educational purposes. I've also experimented with different Linux distributions on Pis. There is of course Pi OS, the officially supported one. However,the major distributions have ARM versions that run on Pis and there are others specifically designed for Pis:

DistributionDescriptionWebsite
Raspberry Pi OSOfficial operating system for Raspberry Pi, based on Debian. Includes a range of educational tools.raspberrypi.org
UbuntuPopular Linux distribution with an official version for Raspberry Pi.ubuntu.com
Manjaro ARMArch-based distribution optimized for ARM devices, including Raspberry Pi.manjaro.org
Kali LinuxSecurity-focused distribution with a version for Raspberry Pi.kali.org
RetroPieDistribution focused on retro gaming emulation for Raspberry Pi.retropie.org.uk
LibreELECMinimalist distribution for running Kodi media center on Raspberry Pi.libreelec.tv
Pi-holeNetwork-wide ad blocker that runs on Raspberry Pi.pi-hole.net
OSMCOpen Source Media Center based on Debian, designed for Raspberry Pi.osmc.tv
RISC OSLightweight operating system originally developed by Acorn Computers, available for Raspberry Pi.riscosopen.org
GentooHighly customizable distribution with an ARM version for Raspberry Pi.gentoo.org
Arch Linux ARMLightweight and flexible distribution for ARM devices, including Raspberry Pi.archlinuxarm.org
DietPiExtremely lightweight Debian-based distribution with a small footprint for Raspberry Pi.dietpi.com
Twister OSDistribution that aims to provide a true desktop computing experience on Raspberry Pi.twisteros.com
Raspbian XP, Raspbian 95Custom distributions based on Raspberry Pi OS with themes mimicking Windows XP and Windows 95.pi-apps.io
BalenaOSContainer-based distribution optimized for IoT devices, including Raspberry Pi.balena.io
LineageOSAndroid-based distribution available for Raspberry Pi.konstakang.com
RecalboxDistribution focused on retro gaming emulation, similar to RetroPie.recalbox.com
LakkaLightweight distribution focused on retro gaming, using RetroArch emulator.lakka.tv
MotionEyeOSDistribution focused on turning Raspberry Pi into a video surveillance system.motioneyeos.org

For instance installing and running Gentoo on one was... an experience.

All in all, Pis are a great way to learn and an even better way to run services at home at a low monetary cost and low power cost.

Over The Wire (Bandit) 🧑‍💻 (2024-07-17)

Link

This is a wargame or ctf game that has the player interact with and penetrate a Linux system. The goal of each level is to retrieve a password or key located somewhere on a server. This can be used to access this next level, which is a user on the server.

SPOILER WARNING

I will provide the prompt and hints to each level and my answers. I may describe my methodology, reasoning, or solution if it is warranted. Do not read if you intend on playing yourself.

Level 0

The goal of this level is for you to log into the game using SSH. The host to which you need to connect is bandit.labs.overthewire.org, on port 2220. The username is bandit0 and the password is bandit0. Once logged in, go to the Level 1 page to find out how to beat Level 1.

Solution

  • ssh bandit0@bandit.labs.overthewire.org -p 2220
  • Once logged in cat readme will output password to level 1.
  • Password: ZjLjTmM6FvvyRnrb2rfNWOZOTa6ip5If

Level 1

The password for the next level is stored in a file called - located in the home directory

  • ssh bandit1@bandit.labs.overthewire.org -p 2220
  • The name of the file containing the password needs to be referenced as a file as - is reserved for other uses in the shell.
  • cat ./- will do the trick
  • Password: 263JGJPfgU6LtdEvgfWU1XP5yac29mFx

Level 2

The password for the next level is stored in a file called spaces in this filename located in the home directory

  • ssh bandit2@bandit.labs.overthewire.org -p 2220
  • This is a similar issue as whitespace has a reserved use is shells as well. The file must be referenced by encasing it with quotes, cat "spaces in this filename" or by escaping the spaces, cat spaces\ in\ this\ filename.
  • Password: MNk8KNH3Usiio41PRUEoDFPqfxLPlSmx

Level 3

The password for the next level is stored in a hidden file in the inhere directory.

  • ssh bandit3@bandit.labs.overthewire.org -p 2220
  • cat inhere/...Hiding-From-You
  • Password: 2WmrDFRmJIq3IPxneAaMGhap0pFhF3NJ

Level 4

The password for the next level is stored in the only human-readable file in the inhere directory. Tip: if your terminal is messed up, try the “reset” command.

  • ssh bandit4@bandit.labs.overthewire.org -p 2220
  • This is the first level that doesn't essentially have a single solution. Essentially do whatever you need to to determine which file is human readable or cat everything to a file and sift through garbage until you see the password.
  • Using file and a wildcard:
bandit4@bandit:~$ file inhere/*
inhere/-file00: data
inhere/-file01: data
inhere/-file02: data
inhere/-file03: data
inhere/-file04: data
inhere/-file05: data
inhere/-file06: data
inhere/-file07: ASCII text
inhere/-file08: data
inhere/-file09: data

Looks to be inhere/-file07.

bandit4@bandit:~$ cat inhere/-file07
4oQYVPkxZOOEOO5pTW81FB8j8lxXGUQw

Level 5

The password for the next level is stored in a file somewhere under the inhere directory and has all of the following properties: human-readable 1033 bytes in size not executable

  • Most automated solution is probably just using find
  • find . -size 1033c \! -executable
bandit5@bandit:~$ find . -size 1033c \! -executable   
./inhere/maybehere07/.file2
  • Can cat this in a one liner by running find in a subshell:
bandit5@bandit:~$ cat $(find . -size 1033c \! -executable)
HWasnPhtq9AVKe0dmk45nxy20cvUa6EG

Level 6

The password for the next level is stored somewhere on the server and has all of the following properties: owned by user bandit7 owned by group bandit6 33 bytes in size

  • Same deal as last level except different switches and searching from root.
  • After running I also redirected stderr to /dev/null because there were too many permission denials getting in the way of reading output
bandit6@bandit:~$ find / -user bandit7 -group bandit6 -size 33c 2>/dev/null                                                 
/var/lib/dpkg/info/bandit7.password
bandit6@bandit:~$
  • And we can cat it in a one liner for fun
bandit6@bandit:~$ cat $(find / -user bandit7 -group bandit6 -size 33c 2>/dev/null)                                          
morbNTDkSW6jIlUc0ymOdMaLnOlFVAaj
bandit6@bandit:~$

Level 7

The password for the next level is stored in the file data.txt next to the word millionth

  • First instinct is to cat then pipe into grep for "millionth".
cat data.txt | grep millionth
millionth	dfwvzFQi4mU0wfNbFOe9RoWskMLg7eEc
bandit7@bandit:~$
  • Yup

Level 8

The password for the next level is stored in the file data.txt and is the only line of text that occurs only once

  • First instinct is to cat then pipe into uniq maybe.
  • My first instinct, cat data.txt | uniq -u, contains too many entries. After researching I realize that repeated lines need to be adjacent to be detected as repeated, so let's sort then pipe into uniq.
bandit8@bandit:~$ sort data.txt | uniq -u                                                                                   
4CKMh1JI91bUIZZPXDqGanal4xvAg0JM
bandit8@bandit:~$
  • Got it

Level 9

The password for the next level is stored in the file data.txt in one of the few human-readable strings, preceded by several ‘=’ characters.

  • We can use strings to convert the garbage data to text, then grep the file for some "=".
bandit9@bandit:~$ strings data.txt -d  | grep ==
[========== the
T%========== passwordG
}========== ist"
========== FGUW5ilLVJrxX9kMYMmlN4MgbpfMiqey
bandit9@bandit:~$
  • Password: FGUW5ilLVJrxX9kMYMmlN4MgbpfMiqey

Level 10

The password for the next level is stored in the file data.txt, which contains base64 encoded data

From wikipedia: >In computer programming, Base64 is a group of binary-to-text encoding schemes that transforms binary data into a sequence of printable characters, limited to a set of 64 unique characters. More specifically, the source binary data is taken 6 bits at a time, then this group of 6 bits is mapped to one of 64 unique characters.

  • I can use base64 to decode the data by piping into it from cat.
bandit10@bandit:~$ cat data.txt | base64 -d 
The password is dtR173fZKb0RRsDFSGsg2RWnpNVj3qRr
  • Success!

Level 11

The password for the next level is stored in the file data.txt, where all lowercase (a-z) and uppercase (A-Z) letters have been rotated by 13 positions

tr can be used to effectively rotate every character back.

bandit11@bandit:~$ cat data.txt | tr 'a-z' 'n-za-m' | tr 'A-Z' 'N-ZA-M'                                                     
The password is 7x16WNeHIi5YkIhWsfFIqoognUTyj9Q4

I need to learn tr syntax, I just found the implementation of Rot13 in tr online and added rotation for capitals as well and piped the output a second time. That worked.

Level 12

The password for the next level is stored in the file data.txt, which is a hexdump of a file that has been repeatedly compressed. For this level it may be useful to create a directory under /tmp in which you can work. Use mkdir with a hard to guess directory name. Or better, use the command “mktemp -d”. Then copy the datafile using cp, and rename it using mv (read the manpages!)

  • mkdir /tmp/sm;cp data.txt /tmp/sm/; cd /tmp/sm
  • I will probably have to convert from hex to binary or something and uncompress that multiple times
  • xxd -r data.txt | gzip -d > out
  • xxd can convert data from hex to binary and vice-versa.
  • bzip2 out -d -c > out2
  • gzip out2 -d -c > out3
  • tar -xvf out3
  • tar -xvf data5.bin
  • bzip2 data6.bin -d -c > out7
  • tar -xvf out7
  • gzip data8.bin -d -c > out9
bandit12@bandit:/tmp/sm$ cat out9
The password is FO5dwFsc0cbaIiH0h8J2eUks2vdTDwAn
bandit12@bandit:/tmp/sm$
  • I gave up on renaming every time so the scheme is inconsistent, but I just checked the output using file every time to determine what decompression algorithm or archival tool to use until it was completely unwrapped as a text file.
  • Password: FO5dwFsc0cbaIiH0h8J2eUks2vdTDwAn

Level 13

The password for the next level is stored in /etc/bandit_pass/bandit14 and can only be read by user bandit14. For this level, you don’t get the next password, but you get a private SSH key that can be used to log into the next level. Note: localhost is a hostname that refers to the machine you are working on

bandit13@bandit:~$ cat sshkey.private 
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxkkOE83W2cOT7IWhFc9aPaaQmQDdgzuXCv+ppZHa++buSkN+
gg0tcr7Fw8NLGa5+Uzec2rEg0WmeevB13AIoYp0MZyETq46t+jk9puNwZwIt9XgB
ZufGtZEwWbFWw/vVLNwOXBe4UWStGRWzgPpEeSv5Tb1VjLZIBdGphTIK22Amz6Zb
ThMsiMnyJafEwJ/T8PQO3myS91vUHEuoOMAzoUID4kN0MEZ3+XahyK0HJVq68KsV
ObefXG1vvA3GAJ29kxJaqvRfgYnqZryWN7w3CHjNU4c/2Jkp+n8L0SnxaNA+WYA7
jiPyTF0is8uzMlYQ4l1Lzh/8/MpvhCQF8r22dwIDAQABAoIBAQC6dWBjhyEOzjeA
J3j/RWmap9M5zfJ/wb2bfidNpwbB8rsJ4sZIDZQ7XuIh4LfygoAQSS+bBw3RXvzE
pvJt3SmU8hIDuLsCjL1VnBY5pY7Bju8g8aR/3FyjyNAqx/TLfzlLYfOu7i9Jet67
xAh0tONG/u8FB5I3LAI2Vp6OviwvdWeC4nOxCthldpuPKNLA8rmMMVRTKQ+7T2VS
nXmwYckKUcUgzoVSpiNZaS0zUDypdpy2+tRH3MQa5kqN1YKjvF8RC47woOYCktsD
o3FFpGNFec9Taa3Msy+DfQQhHKZFKIL3bJDONtmrVvtYK40/yeU4aZ/HA2DQzwhe
ol1AfiEhAoGBAOnVjosBkm7sblK+n4IEwPxs8sOmhPnTDUy5WGrpSCrXOmsVIBUf
laL3ZGLx3xCIwtCnEucB9DvN2HZkupc/h6hTKUYLqXuyLD8njTrbRhLgbC9QrKrS
M1F2fSTxVqPtZDlDMwjNR04xHA/fKh8bXXyTMqOHNJTHHNhbh3McdURjAoGBANkU
1hqfnw7+aXncJ9bjysr1ZWbqOE5Nd8AFgfwaKuGTTVX2NsUQnCMWdOp+wFak40JH
PKWkJNdBG+ex0H9JNQsTK3X5PBMAS8AfX0GrKeuwKWA6erytVTqjOfLYcdp5+z9s
8DtVCxDuVsM+i4X8UqIGOlvGbtKEVokHPFXP1q/dAoGAcHg5YX7WEehCgCYTzpO+
xysX8ScM2qS6xuZ3MqUWAxUWkh7NGZvhe0sGy9iOdANzwKw7mUUFViaCMR/t54W1
GC83sOs3D7n5Mj8x3NdO8xFit7dT9a245TvaoYQ7KgmqpSg/ScKCw4c3eiLava+J
3btnJeSIU+8ZXq9XjPRpKwUCgYA7z6LiOQKxNeXH3qHXcnHok855maUj5fJNpPbY
iDkyZ8ySF8GlcFsky8Yw6fWCqfG3zDrohJ5l9JmEsBh7SadkwsZhvecQcS9t4vby
9/8X4jS0P8ibfcKS4nBP+dT81kkkg5Z5MohXBORA7VWx+ACohcDEkprsQ+w32xeD
qT1EvQKBgQDKm8ws2ByvSUVs9GjTilCajFqLJ0eVYzRPaY6f++Gv/UVfAPV4c+S0
kAWpXbv5tbkkzbS0eaLPTKgLzavXtQoTtKwrjpolHKIHUz6Wu+n4abfAIRFubOdN
/+aLoRQ0yBDRbdXMsZN/jvY44eM+xRLdRVyMmdPtP8belRi2E2aEzA==
-----END RSA PRIVATE KEY-----
  • I will copy this key to my host's ~/.ssh directory and login by forcing the use of the key for access: ssh bandit14@bandit.labs.overthewire.org -p 2220 -i .ssh/id_bandit14
  • I'm in!

Level 14

The password for the next level can be retrieved by submitting the password of the current level to port 30000 on localhost.

  • I can cat the password referenced in the last level and pipe it into netcat to send it to the port.
bandit14@bandit:~$ cat /etc/bandit_pass/bandit14 | netcat localhost  30000                                                  
Correct!
8xCjnmgoKbGLhHFAZlGE5Tmu4M2tKJQo

Level 15

The password for the next level can be retrieved by submitting the password of the current level to port 30001 on localhost using SSL encryption. Helpful note: Getting “HEARTBEATING” and “Read R BLOCK”? Use -ign_eof and read the “CONNECTED COMMANDS” section in the manpage. Next to ‘R’ and ‘Q’, the ‘B’ command also works in this version of that command…

  • I will need to encrypt what I send to the port beforehand. This can be acchomplished with openssl's s_client.
  • From the man page: >DESCRIPTION This command implements a generic SSL/TLS client which connects to a remote host using SSL/TLS. It is a very useful diagnostic tool for SSL servers.

openssl s_client -ign_eof -connect localhost:30001

  • I then manually enter the password
8xCjnmgoKbGLhHFAZlGE5Tmu4M2tKJQo
Correct!
kSkvUpMQ7lBYyCM4GBPvCvT1BfWRy0Dx

closed
bandit15@bandit:~$
  • Mission accomplished!

Level 16

The credentials for the next level can be retrieved by submitting the password of the current level to a port on localhost in the range 31000 to 32000. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.

  • I will search for candidate ports
bandit16@bandit:~$ netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
netstat: no support for `AF INET (tcp)' on this system.
tcp6       0      0 :::31691                :::*                    LISTEN      -                   
tcp6       0      0 :::31046                :::*                    LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   
tcp6       0      0 :::2232                 :::*                    LISTEN      -                   
tcp6       0      0 :::2231                 :::*                    LISTEN      -                   
tcp6       0      0 :::2230                 :::*                    LISTEN      -                   
tcp6       0      0 :::2220                 :::*                    LISTEN      -                   
tcp6       0      0 :::31960                :::*                    LISTEN      -                   
bandit16@bandit:~$
  • 31691, 31046, and 31960 are candidates
  • However none are over ssl, the port may be open but not listening. I can scan with nmap.
nmap -p 31000-32000 localhost     
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-07-16 01:36 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00014s latency).
Not shown: 996 closed tcp ports (conn-refused)
PORT      STATE SERVICE
31046/tcp open  unknown
31518/tcp open  unknown
31691/tcp open  unknown
31790/tcp open  unknown
31960/tcp open  unknown

Nmap done: 1 IP address (1 host up) scanned in 0.11 seconds
  • I will not manually check each with s_client.
openssl s_client -ign_eof -connect localhost:31790 
kSkvUpMQ7lBYyCM4GBPvCvT1BfWRy0Dx
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqbu9AlbssgTcCXkMQnPw9nC
YNN6DDP2lbcBrvgT9YCNL6C+ZKufD52yOQ9qOkwFTEQpjtF4uNtJom+asvlpmS8A
vLY9r60wYSvmZhNqBUrj7lyCtXMIu1kkd4w7F77k+DjHoAXyxcUp1DGL51sOmama
+TOWWgECgYEA8JtPxP0GRJ+IQkX262jM3dEIkza8ky5moIwUqYdsx0NxHgRRhORT
8c8hAuRBb2G82so8vUHk/fur85OEfc9TncnCY2crpoqsghifKLxrLgtT+qDpfZnx
SatLdt8GfQ85yA7hnWWJ2MxF3NaeSDm75Lsm+tBbAiyc9P2jGRNtMSkCgYEAypHd
HCctNi/FwjulhttFx/rHYKhLidZDFYeiE/v45bN4yFm8x7R/b0iE7KaszX+Exdvt
SghaTdcG0Knyw1bpJVyusavPzpaJMjdJ6tcFhVAbAjm7enCIvGCSx+X3l5SiWg0A
R57hJglezIiVjv3aGwHwvlZvtszK6zV6oXFAu0ECgYAbjo46T4hyP5tJi93V5HDi
Ttiek7xRVxUl+iU7rWkGAXFpMLFteQEsRr7PJ/lemmEY5eTDAFMLy9FL2m9oQWCg
R8VdwSk8r9FGLS+9aKcV5PI/WEKlwgXinB3OhYimtiG2Cg5JCqIZFHxD6MjEGOiu
L8ktHMPvodBwNsSBULpG0QKBgBAplTfC1HOnWiMGOU3KPwYWt0O6CdTkmJOmL8Ni
blh9elyZ9FsGxsgtRBXRsqXuz7wtsQAgLHxbdLq/ZJQ7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----

closed
bandit16@bandit:~$
  • It was port 31790 and a key was returned, I will add it to my host's ~/.ssh. ssh bandit17@bandit.labs.overthewire.org -p 2220 -i ~/.ssh/id_bandit17 works!

Level 17

There are 2 files in the homedirectory: passwords.old and passwords.new. The password for the next level is in passwords.new and is the only line that has been changed between passwords.old and passwords.new NOTE: if you have solved this level and see ‘Byebye!’ when trying to log into bandit18, this is related to the next level, bandit19

  • We can just diff to find the differing line:
bandit17@bandit:~$ diff passwords.new passwords.old 
42c42
< x2gLTTjFwMOhQ8oWNbMN362QKxfRqGlO
---
> FtePUTiLiwPzjIFw2T7o57oBS4zUvPpg

So the password is: x2gLTTjFwMOhQ8oWNbMN362QKxfRqGlO

Level 18

The password for the next level is stored in a file readme in the homedirectory. Unfortunately, someone has modified .bashrc to log you out when you log in with SSH.

  • I know that you can pass a command to ssh to be ran rather than initializing a shell
  • ssh bandit18@bandit.labs.overthewire.org -p 2220 'cat readme'
  • The password was returned:
bandit18@bandit.labs.overthewire.org's password: cGWpMaKXVwDUNgPAVJbWYuGHVn9zl3j8

Level 19

To gain access to the next level, you should use the setuid binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit_pass), after you have used the setuid binary.

bandit19@bandit:~$ ./bandit20-do 
Run a command as another user.
  Example: ./bandit20-do id
  • Evidently, we can use this binary to cat bandit20's password since it is the owner of the file that contains it.
bandit19@bandit:~$ ./bandit20-do cat /etc/bandit_pass/bandit20                                                              
0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO

Level 20

There is a setuid binary in the homedirectory that does the following: it makes a connection to localhost on the port you specify as a commandline argument. It then reads a line of text from the connection and compares it to the password in the previous level (bandit20). If the password is correct, it will transmit the password for the next level (bandit21). NOTE: Try connecting to your own network daemon to see if it works as you think

  • I believe I have to connect to a port of my choosing using the suconnect binary and then send the password to that port while it is open. I have some options. I can either use a multiplexer or throw suconnect's process to the background.
  • I am mistaken, it it the other way around. I must send the password to the port first, then suconnect grabs it.
bandit20@bandit:~$ echo -n "0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO" | netcat -l -p 30003 &                                     
[1] 867141
bandit20@bandit:~$ ./suconnect 30003                                                     
Read: 0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO
Password matches, sending next password
EeoULMCra2q0dSkYj561DX7s1CpBuOBt
[1]+  Done                    echo -n "0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO" | netcat -l -p 30003
  • Password: EeoULMCra2q0dSkYj561DX7s1CpBuOBt

Level 21

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.

bandit21@bandit:~$ cat /etc/cron.d/cronjob_bandit22
@reboot bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
bandit21@bandit:~$ cat /usr/bin/cronjob_bandit22.sh
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
bandit21@bandit:~$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
tRae0UfB9v0UzbCdn9cY0gQnds9GF58Q
bandit21@bandit:~$

Password: tRae0UfB9v0UzbCdn9cY0gQnds9GF58Q

Level 22

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed. NOTE: Looking at shell scripts written by other people is a very useful skill. The script for this level is intentionally made easy to read. If you are having problems understanding what it does, try executing it to see the debug information it prints.

bandit22@bandit:~$ cat /etc/cron.d/cronjob_bandit23
@reboot bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
* * * * * bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
bandit22@bandit:~$ cat /usr/bin/cronjob_bandit23.sh
#!/bin/bash

myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)

echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"

cat /etc/bandit_pass/$myname > /tmp/$mytarget
bandit22@bandit:~$
  • Based on this, the password whose name was hashed by md5sum
  • I will manually run the command using "bandit23" as myname in a subshell and cat the appropriate file.
bandit22@bandit:~$ cat /tmp/$(echo I am user bandit23 | md5sum | cut -d ' ' -f 1)
0Zf11ioIjMVN551jX3CmStKLYqjk54Ga

Level 23

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed. NOTE: This level requires you to create your own first shell-script. This is a very big step and you should be proud of yourself when you beat this level! NOTE 2: Keep in mind that your shell script is removed once executed, so you may want to keep a copy around…

bandit23@bandit:~$ cat /etc/cron.d/cronjob_bandit24 
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
* * * * * bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
bandit23@bandit:~$ cat /usr/bin/cronjob_bandit24.sh
#!/bin/bash

myname=$(whoami)

cd /var/spool/$myname/foo
echo "Executing and deleting all scripts in /var/spool/$myname/foo:"
for i in * .*;
do
    if [ "$i" != "." -a "$i" != ".." ];
    then
        echo "Handling $i"
        owner="$(stat --format "%U" ./$i)"
        if [ "${owner}" = "bandit23" ]; then
            timeout -s 9 60 ./$i
        fi
        rm -f ./$i
    fi
done
  • Based on the script that is being run by cron, we just need to write a script that gets the name of bandit24's password for us. This script executes every script in /var/spool/bandit24/foo/ if it is owned by bandit23 then deletes it. However, the script will be ran as bandit24 since it is that user's cronjob. Therefore, I can get the contents of /etc/bandit_pass from a script in /var/spool/bandit24/foo/.
  • I am having an issue getting output from the script presumably due to permissions. I modified the target directory with chmod 777.
#!/bin/bash
cat /etc/bandit_pass/bandit24 >> /tmp/sm2/out.txt

This did the trick: gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8

  • Success!

Level 24

A daemon is listening on port 30002 and will give you the password for bandit25 if given the password for bandit24 and a secret numeric 4-digit pincode. There is no way to retrieve the pincode except by going through all of the 10000 combinations, called brute-forcing. You do not need to create new connections each time

  • This is the script I've formulated:
#!/bin/sh

code=0
while [ $code -le 9998 ];
do
        code=$((code+1))
        pass="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 ${code}"

        echo "Trying code $pass"
        echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
done
  • But it is very slow, there must be a faster way.
  • Firstly, it starts at 0 because it just increments it doesn't handle every digit independently.
#!/bin/bash

for i in {0000..9999}
do
  pass="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 ${i}"
  echo "Trying code $pass"
  echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
done
  • This is better! Didn't know bash supported iterating over ranges this way. Now looking into improving speed. Could utilize parallelization in some way. I could:
    • Throw the jobs into the background with a max number running any time
    • Utilize parallel
#!/bin/bash

export pass_prefix="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 "

generate_and_try() {
  i=$1
  pass="${pass_prefix}${i}"
  echo "Trying code $pass"
  echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
}

export -f generate_and_try
export pass_prefix

# Generate the sequence and run in parallel
seq -w 0000 9999 | parallel -j 100 generate_and_try
  • parallel handles the parallelization... luckily it is installed...
  • Instead of a loop this solution utilizes seq to generate codes
  • The code is passed as a cmdline arg
  • I will then search the output for the string "Correct". One could also grep -v the string "Wrong".
Correct! The password of user bandit25 is iCi86ttT4KSNe1armKiwbQNmB3YJP3q4
  • Success!

Level 25

Logging in to bandit26 from bandit25 should be fairly easy… The shell for user bandit26 is not /bin/bash, but something else. Find out what it is, how it works and how to break out of it.

  • I know that default shells are in /etc/passwd.
  • cat /etc/passwd | grep -i bandit26 yields bandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
  • showtext is a script:

#!/bin/sh

export TERM=linux

exec more ~/text.txt exit 0

* And there is a key in the home directory 
```terminal
ls                                                                                                       
bandit26.sshkey
bandit25@bandit:~$ cat bandit26.sshkey 
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEApis2AuoooEqeYWamtwX2k5z9uU1Afl2F8VyXQqbv/LTrIwdW
pTfaeRHXzr0Y0a5Oe3GB/+W2+PReif+bPZlzTY1XFwpk+DiHk1kmL0moEW8HJuT9
/5XbnpjSzn0eEAfFax2OcopjrzVqdBJQerkj0puv3UXY07AskgkyD5XepwGAlJOG
xZsMq1oZqQ0W29aBtfykuGie2bxroRjuAPrYM4o3MMmtlNE5fC4G9Ihq0eq73MDi
1ze6d2jIGce873qxn308BA2qhRPJNEbnPev5gI+5tU+UxebW8KLbk0EhoXB953Ix
3lgOIrT9Y6skRjsMSFmC6WN/O7ovu8QzGqxdywIDAQABAoIBAAaXoETtVT9GtpHW
qLaKHgYtLEO1tOFOhInWyolyZgL4inuRRva3CIvVEWK6TcnDyIlNL4MfcerehwGi
il4fQFvLR7E6UFcopvhJiSJHIcvPQ9FfNFR3dYcNOQ/IFvE73bEqMwSISPwiel6w
e1DjF3C7jHaS1s9PJfWFN982aublL/yLbJP+ou3ifdljS7QzjWZA8NRiMwmBGPIh
Yq8weR3jIVQl3ndEYxO7Cr/wXXebZwlP6CPZb67rBy0jg+366mxQbDZIwZYEaUME
zY5izFclr/kKj4s7NTRkC76Yx+rTNP5+BX+JT+rgz5aoQq8ghMw43NYwxjXym/MX
c8X8g0ECgYEA1crBUAR1gSkM+5mGjjoFLJKrFP+IhUHFh25qGI4Dcxxh1f3M53le
wF1rkp5SJnHRFm9IW3gM1JoF0PQxI5aXHRGHphwPeKnsQ/xQBRWCeYpqTme9amJV
tD3aDHkpIhYxkNxqol5gDCAt6tdFSxqPaNfdfsfaAOXiKGrQESUjIBcCgYEAxvmI
2ROJsBXaiM4Iyg9hUpjZIn8TW2UlH76pojFG6/KBd1NcnW3fu0ZUU790wAu7QbbU
i7pieeqCqSYcZsmkhnOvbdx54A6NNCR2btc+si6pDOe1jdsGdXISDRHFb9QxjZCj
6xzWMNvb5n1yUb9w9nfN1PZzATfUsOV+Fy8CbG0CgYEAifkTLwfhqZyLk2huTSWm
pzB0ltWfDpj22MNqVzR3h3d+sHLeJVjPzIe9396rF8KGdNsWsGlWpnJMZKDjgZsz
JQBmMc6UMYRARVP1dIKANN4eY0FSHfEebHcqXLho0mXOUTXe37DWfZza5V9Oify3
JquBd8uUptW1Ue41H4t/ErsCgYEArc5FYtF1QXIlfcDz3oUGz16itUZpgzlb71nd
1cbTm8EupCwWR5I1j+IEQU+JTUQyI1nwWcnKwZI+5kBbKNJUu/mLsRyY/UXYxEZh
ibrNklm94373kV1US/0DlZUDcQba7jz9Yp/C3dT/RlwoIw5mP3UxQCizFspNKOSe
euPeaxUCgYEAntklXwBbokgdDup/u/3ms5Lb/bm22zDOCg2HrlWQCqKEkWkAO6R5
/Wwyqhp/wTl8VXjxWo+W+DmewGdPHGQQ5fFdqgpuQpGUq24YZS8m66v5ANBwd76t
IZdtF5HXs2S5CADTwniUS5mX1HO9l5gUkk+h0cH5JnPtsMCnAUM+BRY=
-----END RSA PRIVATE KEY-----
bandit25@bandit:~$
  • The solution for this was ultimately simple yet very elusive. So the text contained in ~text.txt was too short to do anything with and would immeditaly exit. I explored for any possible ssh switch or techqiue I could employ. I checked every permission. But the simpliest solution was just... to make the window smaller... That forces more to enter an interactive mode since all the text can't be displayed. From there you cna evert Vi and do whatever you need to.
  • I first redefined the shell:
  • :set shell=/bin/bash
  • And enter a shell from Vi using:shell
  • Now I am in and technically in:

Level 26

Good job getting a shell! Now hurry and grab the password for bandit27!

  • Then catted the password
    bandit26@bandit:~$ cat /etc/bandit_pass/bandit26
    s0773xxkk0MXfdqOfPRVr9L3jJBUOgCZ
    

bandit26@bandit:~$ ```

  • Password: s0773xxkk0MXfdqOfPRVr9L3jJBUOgCZ
  • Remember this is just bandit 26's password.
bandit26@bandit:~$ ls -l
total 20
-rwsr-x--- 1 bandit27 bandit26 14880 Jul 17 15:57 bandit27-do
-rw-r----- 1 bandit26 bandit26   258 Jul 17 15:57 text.txt
bandit26@bandit:~$ ./bandit27-do cat /etc/bandit_pass/bandit27
upsNCc7vzaRDx6oZC6GiR6ERwe1MowGB
bandit26@bandit:~$
  • Looks like there is a binary with the suid bit set allowing me to run it as bandit27 since they are the owner and bandit26's group has execute permissions on. The binary evidently takes a command as an argument to be ran. I used this to get the password for bandit27.
  • Password: upsNCc7vzaRDx6oZC6GiR6ERwe1MowGB

Level 27

There is a git repository at ssh://bandit27-git@localhost/home/bandit27-git/repo via the port 2220. The password for the user bandit27-git is the same as for the user bandit27.

Clone the repository and find the password for the next level.

  • I make a directory in tmp and clone the repo
bandit27@bandit:/tmp/gh$ git clone ssh://bandit27-git@localhost:2220/home/bandit27-git/repo
bandit27@bandit:/tmp/gh/repo$ cat README 
The password to the next level is: Yz9IpL0sBcCeuG7m9uQFt8ZNpS4HZRcN
  • There was simply a README containing the password

Level 28

There is a git repository at ssh://bandit28-git@localhost/home/bandit28-git/repo via the port 2220. The password for the user bandit28-git is the same as for the user bandit28. Clone the repository and find the password for the next level.

  • It is the same process as before, but the contents are little different.
bandit28@bandit:/tmp/gh28/repo$ ls
README.md
bandit28@bandit:/tmp/gh28/repo$ cat README.md 
# Bandit Notes
Some notes for level29 of bandit.

## credentials

- username: bandit29
- password: xxxxxxxxxx

bandit28@bandit:/tmp/gh28/repo$
  • Looks like we will have to brute for a password a 10 character password, which would take way too long. As in like millions of years... using a supercomputer... so this can't be the solution.
bandit28@bandit:/tmp/gh28/repo$ git log
WARNING: terminal is not fully functional
Press RETURN to continue 
commit 8cbd1e08d1879415541ba19ddee3579e80e3f61a (HEAD -> mast
er, origin/master, origin/HEAD)
Author: Morla Porla <morla@overthewire.org>
Date:   Wed Jul 17 15:57:30 2024 +0000

    fix info leak

commit 73f5d0435070c8922da12177dc93f40b2285e22a
Author: Morla Porla <morla@overthewire.org>
Date:   Wed Jul 17 15:57:30 2024 +0000

    add missing data

commit 5f7265568c7b503b276ec20f677b68c92b43b712
Author: Ben Dover <noone@overthewire.org>
Date:   Wed Jul 17 15:57:30 2024 +0000

    initial commit of README.md
bandit28@bandit:/tmp/gh28/repo$
  • The solution looks it is going to be looking at each commit to see when a password added. This can be a accomplished with checkout. There seems to be three commits and the password was ultimately in the middle one.
bandit28@bandit:/tmp/gh28/repo$ git checkout 73f5d0435070c8922da12177dc93f40b2285e22a
Previous HEAD position was 5f72655 initial commit of README.md
HEAD is now at 73f5d04 add missing data
bandit28@bandit:/tmp/gh28/repo$ ls
README.md
bandit28@bandit:/tmp/gh28/repo$ cat README.md 
# Bandit Notes
Some notes for level29 of bandit.

## credentials

- username: bandit29
- password: 4pT1t5DENaYuqnqvadYs1oE4QLCdjmJ7

bandit28@bandit:/tmp/gh28/repo$ 
  • Password: 4pT1t5DENaYuqnqvadYs1oE4QLCdjmJ7

Level 29

There is a git repository at ssh://bandit29-git@localhost/home/bandit29-git/repo via the port 2220. The password for the user bandit29-git is the same as for the user bandit29. Clone the repository and find the password for the next level.

bandit29@bandit:/tmp/b29/repo$ cat README.md 
# Bandit Notes
Some notes for bandit30 of bandit.

## credentials

- username: bandit30
- password: <no passwords in production!>

bandit29@bandit:/tmp/b29/repo$
  • Probably going to have to go to a different branch based on this.
bandit29@bandit:/tmp/b29/repo$ git branch -r
WARNING: terminal is not fully functional
Press RETURN to continue 
  origin/HEAD -> origin/master
  origin/dev
  origin/master
  origin/sploits-dev
bandit29@bandit:/tmp/b29/repo$
  • I'll checkout dev
bandit29@bandit:/tmp/b29/repo$ git checkout dev
Previous HEAD position was 5a53eb8 initial commit of README.md
branch 'dev' set up to track 'origin/dev'.
Switched to a new branch 'dev'
bandit29@bandit:/tmp/b29/repo$ ls
code  README.md
bandit29@bandit:/tmp/b29/repo$ ls code/
gif2ascii.py
bandit29@bandit:/tmp/b29/repo$ cat README.md 
# Bandit Notes
Some notes for bandit30 of bandit.

## credentials

- username: bandit30
- password: qp30ex3VLz5MDG1n91YowTv4Q8l7CDZL

bandit29@bandit:/tmp/b29/repo$
  • There it is! Password: qp30ex3VLz5MDG1n91YowTv4Q8l7CDZL

Level 30

There is a git repository at ssh://bandit30-git@localhost/home/bandit30-git/repo via the port 2220. The password for the user bandit30-git is the same as for the user bandit30. Clone the repository and find the password for the next level.

bandit30@bandit:/tmp/b30/repo$ cat README.md 
just an epmty file... muahaha
bandit30@bandit:/tmp/b30/repo$ git tag
WARNING: terminal is not fully functional
Press RETURN to continue 
secret
bandit30@bandit:/tmp/b30/repo$ git show secret
WARNING: terminal is not fully functional
Press RETURN to continue 
fb5S2xb7bRyFmAvQYQGEqsbhVyJqhnDy
bandit30@bandit:/tmp/b30/repo$
  • The README had nothing, but there was a tag named secret that contained the password.
  • Password: fb5S2xb7bRyFmAvQYQGEqsbhVyJqhnDy

Level 31

There is a git repository at ssh://bandit31-git@localhost/home/bandit31-git/repo via the port 2220. The password for the user bandit31-git is the same as for the user bandit31. Clone the repository and find the password for the next level.

bandit31@bandit:/tmp/b31/repo$ cat README.md 
This time your task is to push a file to the remote repository.

Details:
    File name: key.txt
    Content: 'May I come in?'
    Branch: master

bandit31@bandit:/tmp/b31/repo$
  • Here it seems we must write a file key.txt that contains the required string.
  • We can touch key.txt; echo "May I come in? > key.txt"
  • Then add key.txt, commit, then push.
  • The .gitignore needed to be edited. because every text file was being ignored via: *.txt
  • Once pushed we succeeded!
bandit31-git@localhost's password: 
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 2 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 321 bytes | 321.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
remote: ### Attempting to validate files... ####
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
remote: Well done! Here is the password for the next level:
remote: 3O9RfhqyAlVBEZpVb6LYStshZoqoSx5K 
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
To ssh://localhost:2220/home/bandit31-git/repo
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://localhost:2220/home/bandit31-git/repo'
bandit31@bandit:/tmp/b31/repo$
  • Password: 3O9RfhqyAlVBEZpVb6LYStshZoqoSx5K

Level 32

After all this git stuff, it’s time for another escape. Good luck!

WELCOME TO THE UPPERCASE SHELL
>> ls
sh: 1: LS: Permission denied

Where am I?

  • We can't use commands because they are all made uppercase. In this peculiar situation we'd have access to environment variables and command line arguments however. Considering that the first arg, $0, is the shell itself, i can call a new shell with it?
>> $0
$ 
  • YES!
  • I switched to a bash shell and got the next password
bandit33@bandit:~$ cat /etc/bandit_pass/bandit33
tQdtbs5D5i2vJwkO8mEyYEyTL8izoeJ0
bandit33@bandit:~$ 

Level 33

At this moment, level 34 does not exist yet.

bandit33@bandit:~$ cat README.txt 
Congratulations on solving the last level of this game!

At this moment, there are no more levels to play in this game. However, we are constantly working
on new levels and will most likely expand this game with more levels soon.
Keep an eye out for an announcement on our usual communication channels!
In the meantime, you could play some of our other wargames.
us
If you have an idea for an awesome new level, please let us know!
bandit33@bandit:~$

I WON! 🥳


What I Learned

This game was very fun and forces us to really think about how certain aspects of a Linux system works and how they interact with one another. The topics that are generally touched on are:

  • Basic command line utilities
    • ls, cd, mkdir, etc.
  • Text manipulation
    • cat, grep, uniq, sort, seq, strings, tr
  • Redirection
    • Redirection Operators, Pipes, tee
  • Permissions
  • Remote Access and Remote Command Execution
    • ssh
  • System File Locations and Root Directories
    • etc/passwd, /tmp, `/bin
  • Processes
    • &, bg, fg, tmux, screen, ps
  • Scheduling
    • cron
  • Shells
    • bash, sh
    • Environment Variables and Arguments, $0, TERM
  • Base Conversions, Encoding, and Hashing
    • base64, md5sum
  • Compression and Archiving
    • tar, gzip, bzip2
  • Basic networking Concepts and Utilities
    • nc, netstat
  • Scripting
    • Conditionals, Comparisons, Loops
    • Optionally parallelization through parallel
  • Git Concepts and Subcommands
    • checkout, branch, tag, add, commit, push

Basic Calculus in C (2024-07-10)

Numerical Methods of Differentiation

I just wrote this up because I was curious about how to code calculus stuff which I had never done before. This lead me to falling down a rabbit hole on numerical methods.

Anyone who has taken Calculus in school is familiar with some numerical methods of differentiation or integration. The basis of the definition of a derivative is itself an approximation:

\[ f'(x) = \lim_{{h \to 0}} \frac{f(x+h) - f(x)}{h} \]

A secant line where the distance between the two intersections is an infinitesimal.

I've recently learned that this is a class of method known as the Finite Difference Method where a derivative is calculated using the same difference quotient with a finite distance that is sufficiently small:

\[f'(x) \approx \frac{f(x+h) - f(x)}{h}\]

New to me is the Symmetric Difference Quotient which also approximates the slope, but by using two secant lines equidistant from x.

\[f'(x) \approx \frac{f(x+h) - f(x-h)}{2h}\]

The accuracy will be off by a proportion of h using the former method and by h^2 using the latter one.

The accuracy will also be affected by the choice of forward, back, or central difference, round-off error, or truncation error, which funnily enough is often notated using big-O.

Numerical Methods of Integration

Riemann Sums is the other numerical method that is often learned to introduce the concept of an integral. And has been in use since antiquity - like when Archimedes approximated the area of the circle through methods of exhaustion.

Riemann sums partition the area under a curve either from the left, right, or midpoint and if those partitions or slices are sufficiently small, you get a good approximation. This method utilizes rectangles:

\[\int_{a}^{b} f(x) , dx \approx \sum_{i=0}^{n-1} f\left( \frac{x_i + x_{i+1}}{2} \right) \Delta x\]

But can utilize other polygons such a trapezoids:

\[\int_{a}^{b} f(x) , dx \approx \frac{\Delta x}{2} \left[ f(x_0) + 2 \sum_{i=1}^{n-1} f(x_i) + f(x_n) \right]\]

There are a plethora numerical methods for both differentiation and integration that have been developed over the centuries that have their applications in engineering, manufacturing, physics, and computer science.

Numerical Differentiation MethodsNumerical Integration Methods
Finite Difference MethodsBasic Methods
- Forward Difference- Rectangle Rule (Midpoint Rule)
- Backward Difference- Trapezoidal Rule
- Central Difference- Simpson's Rule
Higher-Order Finite Difference MethodsExtended Newton-Cotes Formulas
- Second-Order Forward Difference- Simpson's 3/8 Rule
- Second-Order Backward Difference- Boole's Rule
- Second-Order Central Difference- Newton-Cotes Formulas
- Higher-Order Central DifferencesGaussian Quadrature
Richardson Extrapolation- Gauss-Legendre Quadrature
Spectral Methods- Gauss-Chebyshev Quadrature
- Fourier Spectral Methods- Gauss-Hermite Quadrature
- Chebyshev Spectral Methods- Gauss-Laguerre Quadrature
Spline MethodsRomberg Integration
- Linear Spline DifferentiationAdaptive Quadrature Methods
- Quadratic Spline Differentiation- Adaptive Simpson's Method
- Cubic Spline Differentiation- Adaptive Trapezoidal Method
Polynomial Interpolation MethodsMulti-dimensional Methods
- Lagrange Interpolation Differentiation- Monte Carlo Integration
- Newton's Divided Difference Differentiation- Quasi-Monte Carlo Methods
- Hermite Interpolation Differentiation- Sparse Grid Methods
Least Squares Methods- Cubature Rules
- Least Squares Polynomial DifferentiationSpecialized Methods
Numerical Methods for Specific Problems- Clenshaw-Curtis Quadrature
- Finite Volume Methods- Lobatto Quadrature
- Finite Element Methods- Filon's Method (for oscillatory integrals)
- Boundary Element Methods- Double Exponential Integration
Miscellaneous MethodsNumerical Differentiation Based Methods
- Savitzky-Golay Filter- Richardson Extrapolation
- Automatic Differentiation- Extrapolated Romberg Integration
- Complex Step DifferentiationModern Methods
- Spectral Methods
- Spline-based Methods
- Quadrature by Expansion
- Finite Element Method

Numerical Methods in C

Since these methods discretize functions they are how one could create algorithms to perform differentiation or integration. For example:

// Forward difference method
double forward_difference(double x, double h) {
    return (f(x + h) - f(x)) / h;
}

// Backward difference method
double backward_difference(double x, double h) {
    return (f(x) - f(x - h)) / h;
}

// Central difference method
double central_difference(double x, double h) {
    return (f(x + h) - f(x - h)) / (2 * h);
}

These c function will approximate a derivative given some function.

How about integration:

// Trapezoidal rule function
double trapezoidal(double a, double b, int n) {
    double h = (b - a) / n;
    double sum = 0.5 * (f(a) + f(b));
    
    for (int i = 1; i < n; i++) {
        sum += f(a + i * h);
    }
    
    return sum * h;
}

This will calculate an integral given a number of sub-intervals.

Or this:

// Simpson's rule function
double simpsons(double a, double b, int n) {
    double h = (b - a) / n;
    double sum = f(a) + f(b);
    
    for (int i = 1; i < n; i++) {
        double x = a + i * h;
        if (i % 2 == 0) {
            sum += 2 * f(x);
        } else {
            sum += 4 * f(x);
        }
    }
    
    return sum * h / 3;
}

Which does the same according to Simpson's Rule.

In Conclusion

Numerical methods seem essential to most calculus applications in the real world, however it isn't emphasized at all in the university calculus series. I'm glad I read up on it. I may update this with more advanced methods translated to c.

Rewrites of GNU Utilities (2024-06-27)

There seems to be a modern trend of rewriting common GNU utilities, especially in Rust. The GNU utils have been rewritten before, most notably as BusyBox, the GNU core utils as a single binary meant to be used in extremely small embedded Linux environments. However, Rust seems to be a popular language used to write these newer ones, evidently because Rust is a new darling language. However it seems to have a newfound relevance as rust code was recently added to the Linux kernel.
These rewrites often offer improved functionality over their much older counterparts, have more human readable options, syntax, and outputs, and some even boast greater efficiency and speed. Now, if true, these improvements are likely never human detectable. No person will likely ever feel a difference in speed at a cli, but it is fun to note. Despite these improvements these rewrites will likely never gain widespread use these the originals are already installed and countless scripts and other tools already depend on their existence. But a poweruser who wants to have fun and utilize newer, more powerful and intuitive tools, should have at it. I'd actually recommend many of them, they're amazing. I'd just caution these users to not come too accustomed to using them as if they ever want to become a professional, they'll immediately encounter a situation where only GNU utils are at their disposal. I definitely have to keep this in mind when either using a rewrite or my own aliases.
In this post, I'm going list the ones I personally use and others I've never tried but am interested in.


bat

A cat clone with syntax highlighting and Git integration.
bat

exa

A modern replacement for ls.
exa

lsd

The next gen file listing command. Backwards compatible with ls.
lsd

delta

A viewer for git and diff output
delta

dust

A more intuitive version of du written in rust.
dust

duf

A better df alternative
duf

broot

A new way to see and navigate directory trees
broot

fd

A simple, fast and user-friendly alternative to find.
fd

ripgrep

An extremely fast alternative to grep that respects your gitignore
ripgrep

ag

A code searching tool similar to ack, but faster.
ag

fzf

A general purpose command-line fuzzy finder.
fzf

mcfly

Fly through your shell history. Great Scott!
mcfly

choose

A human-friendly and fast alternative to cut and (sometimes) awk
choose

jq

sed for JSON data.
jq

sd

An intuitive find & replace CLI (sed alternative).
sd

cheat

Create and view interactive cheatsheets on the command-line.
cheat

tldr

A community effort to simplify man pages with practical examples.
tldr

bottom

Yet another cross-platform graphical process/system monitor.
bottom

glances

Glances an Eye on your system. A top/htop alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.
glances

gtop

System monitoring dashboard for terminal.
gtop

hyperfine

A command-line benchmarking tool.
hyperfine

gping

ping, but with a graph.
gping

procs

A modern replacement for ps written in Rust.
procs

httpie

A modern, user-friendly command-line HTTP client for the API era.
httpie

curlie

The power of curl, the ease of use of httpie.
curlie

xh

A friendly and fast tool for sending HTTP requests. It reimplements as much as possible of HTTPie's excellent design, with a focus on improved performance.
xh

zoxide

A smarter cd command inspired by z.
zoxide

dog

A user-friendly command-line DNS client. dig on steroids
dog

Linux Learning Resources (2024-06-26)

I am currently a RHCSA who will eventually be an RHCE. This requires me to keep my skills fresh. The learning seemingly never stops; there is always something else to know. Whether it be a new tool that is really cool, or a facet of something's design that is intriguing or indicates how it can be manipulated.
All this constant learning and re-learning requires resources. I've read an untold number of documentation/wiki articles, and have watched countless Youtube videos on topics relating to Linux. Here, I want to document the resources that have served me best and that have provided the most digestible knowledge. Maybe it will help others. It will be categorized along the lines of format. Also, each resource will be rated from 1-5 penguins 🐧. The more penguins the better.

Books

I find books the worst method of learning Linux. It isn't conducive to hands on learning. However, portions of these books so relay and explain underlying concepts pretty well. Most books take the form of that of a manual that is good for referencing but not learning. And even then, something printed on paper easily becomes outdated. Books that are meant for preparing for a specific exam are better as they often include lab material.

Wikis

In my opinion, wikis are the best written resource. They often succinctly describe the nature of something and provide the most pertinent tools and their use cases. They are also written and maintained by the experts themselves. Examples are often provided as snippets that can be copied and pasted directly into a terminal.

Websites

There are websites out their specifically dedicated to learning Linux. Some are small readings that include a quizzes for example. Others are hands on labs similar to something like HackTheBox. Some are just there to help guide continuing education.

Youtube Channels

The issue with Youtube channels relating to Linux is that they are often not related to administration at all. They are mostly from the perspective of a desktop user, albeit a poweruser. Some may lean towards admin more than others, and some may focus entirely on scripting. But most focus on the industry and landscape in general. Regardless, these are the channels I've watched and enjoyed over the years, and have learned from greatly.

Why mdbook? (2024-06-24)

There are a plethora of static site generation tools out there. One could essentially use any language or framework they desire. My requirements were a tool that is visually and functionally simple. I am not a front end developer, and I have no desire to be one. My first attempt was using a Jekyll template. While Jekyll and it's templates seem decent, they didn't offer the amount of editing capabilities I was looking for. Rather than being locked into a directory structure or toolbar formatting. I've also considered tools like Docusaurus because every website I've seen in it looks nice, but it seems I'd be directly editing source more than I'd like to. Eventually, since I have experience with writing in Markdown, especially with Gitbook and mdbook, I decided to use what I am most familiar with.

Why Markdown is Amazing

Markdown is probably the best text formatting "language" other than Latex. It is simple and portable. It's parsed and ultimately converted into HTML so it can exist essentially anywhere. And tools like Pandoc allow one to convert into into any document format one needs like pdf or even the dreaded troff for man pages. Aside form conversions numerous platforms support markdown natively like Github and the zettelkasten-astic note taking program Obsidian. One could write Markdown in one, and take it essentially anywhere. Notes, webpages, and documentation oh my. And if you need functionality the specific parser you're using doesn't support, many support overriding the defaults because, everything will ultimately be HTML and CSS. You could resort to editing anything you needed to by hand anyway.

mdbook As A Personal Site

The rust🦀 project, mdbook is definitely intended to be used for books, not personal sites. However the chapter bar is functionally a navbar,each, I can still link to other pages from within a page if I have to, and it naturally lends itself to a blog. Now the cons are that mdbook lacks a tagging system. Or any system for automatically maintaining blog posts. However, like I said, I'm not locked into any structure. I can invent any scheme my heart desires through the use of shell scripts and Github actions. I can design a system that assigns names according to a convention, fills in content for posts according to a template, orders the posts by date written, implement some kind os psuedo tagging system, etc. All that being said, I was always looking for something quick and dirt, where I can just market myself and flex my interests. This will do.

Links


Notes

This chapter is where I will dump my notes. Anything is fair game. I use Obsidian to take notes, which uses Markdown, so I can simply copy/paste whatever I write to here.

Cheatsheet DUMP

Bash Cheatsheet

CommandDescription
lsList directory contents
cdChange directory
pwdPrint working directory
cp source destinationCopy files or directories
mv source destinationMove/rename files or directories
rm fileRemove files
mkdir directoryCreate a new directory
rmdir directoryRemove an empty directory
echo "text"Print text to the terminal
cat fileConcatenate and display file content
less fileView file content one screen at a time
grep "pattern" fileSearch for a pattern in a file
find path -name "pattern"Find files and directories
ps auxDisplay currently running processes
kill PIDKill a process by PID
topDisplay and update sorted process list
chmod permissions fileChange file permissions
chown user:group fileChange file owner and group
df -hDisplay disk usage in human-readable format
du -sh directoryDisplay directory size in human-readable format
ln -s target link_nameCreate a symbolic link
alias name='command'Create an alias for a command
export VARIABLE=valueSet an environment variable
historyShow command history
tar -czf archive.tar.gz fileCreate a compressed archive using gzip
tar -xzf archive.tar.gzExtract a compressed archive using gzip
uptimeShow how long the system has been running
whoamiDisplay the current username
sudo commandExecute a command as the superuser
ssh user@hostConnect to a remote host via SSH
scp source user@host:destinationCopy files over SSH
crontab -eEdit cron jobs
jobsList background jobs
bg job_idResume a background job
fg job_idBring a background job to the foreground
nohup command &Run a command immune to hangups
diff file1 file2Compare the contents of two files
source fileRead and execute commands from a file in the current shell

Redirection Cheatsheet

CommandDescription
command > fileRedirect standard output (stdout) to a file (overwrite)
command >> fileRedirect standard output (stdout) to a file (append)
command 2> fileRedirect standard error (stderr) to a file (overwrite)
command 2>> fileRedirect standard error (stderr) to a file (append)
command &> fileRedirect both standard output (stdout) and standard error (stderr) to a file (overwrite)
command &>> fileRedirect both standard output (stdout) and standard error (stderr) to a file (append)
command < fileRedirect input from a file
command <<< "string"Redirect a string as input
command1 \| command2Use the output of command1 as input for command2 (pipe)
command1 \|& command2Pipe both stdout and stderr of command1 to command2 (bash 4.0+)
command > /dev/nullDiscard standard output (stdout)
command 2> /dev/nullDiscard standard error (stderr)
command &> /dev/nullDiscard both standard output (stdout) and standard error (stderr)
command > file 2>&1Redirect stdout to a file and stderr to the same file
command 2>&1 > fileRedirect stderr to the current stdout, then redirect stdout to a file
command1 2>&1 \| command2Redirect both stdout and stderr of command1 to command2
command > file1 2> file2Redirect stdout to file1 and stderr to file2
command < file1 > file2Redirect input from file1 and output to file2
exec > fileRedirect all subsequent stdout in the script to a file
exec 2> fileRedirect all subsequent stderr in the script to a file
exec > /dev/ttyRestore stdout to the terminal
exec 2> /dev/ttyRestore stderr to the terminal
command1 \| tee filePipe output of command1 to file and also display it on the terminal
command1 \| tee -a filePipe output of command1 to file (append) and also display it on the terminal
command << EOFHere document: redirect multiple lines of input to a command until EOF
command <<- EOFHere document with leading tab strip: redirect input until EOF
command <&-Close standard input (stdin)
command >&-Close standard output (stdout)
command 2>&-Close standard error (stderr)

Important System Directories and Files

/etc

Directory/FileDescription
/etc/passwdUser account information
/etc/shadowSecure user account information (passwords)
/etc/groupGroup account information
/etc/gshadowSecure group account information
/etc/fstabFilesystem mount table
/etc/hostsStatic table lookup for hostnames
/etc/resolv.confDNS server information
/etc/hostnameSystem's hostname
/etc/sysconfig/networkBasic network configuration
/etc/sysconfig/network-scripts/Network scripts and configuration files
/etc/crontabCron job schedule
/etc/cron.d/Additional cron job schedules
/etc/ssh/sshd_configSSH server configuration
/etc/sudoerssudo configuration file
/etc/systemd/system/Systemd unit files for services and targets
/etc/selinux/configSELinux configuration file
/etc/yum.confYUM package manager configuration
/etc/yum.repos.d/Repository configuration files for YUM

/var

Directory/FileDescription
/var/log/Directory containing log files
/var/log/messagesGeneral system log file
/var/log/secureSecurity and authentication log
/var/log/audit/Audit log files
/var/log/dmesgKernel ring buffer log
/var/log/httpd/Apache HTTP server logs
/var/spool/cron/User crontab files
/var/spool/mail/User mail files
/var/lib/Variable state information
/var/lib/mysql/MySQL database files
/var/lib/pgsql/PostgreSQL database files
/var/www/html/Default directory for web server content

/usr

Directory/FileDescription
/usr/bin/User binaries
/usr/sbin/System binaries
/usr/local/Local software and custom scripts
/usr/share/Shared data and resources for applications
/usr/lib/Libraries for binaries in /usr/bin and /usr/sbin
/usr/lib64/64-bit libraries
/usr/include/Header files for C programming
/usr/src/Source code files
/usr/share/doc/Documentation files for installed packages
/usr/share/man/Manual pages

/boot

Directory/FileDescription
/boot/vmlinuz-Linux kernel image
/boot/initramfs-Initial RAM filesystem
/boot/grub2/GRUB 2 bootloader configuration and files
/boot/efi/EFI boot files

/proc

Directory/FileDescription
/proc/cpuinfoCPU information
/proc/meminfoMemory information
/proc/versionKernel version
/proc/cmdlineKernel command line
/proc/devicesDevice information
/proc/diskstatsDisk statistics
/proc/uptimeSystem uptime
/proc/loadavgSystem load average
/proc/mountsMounted filesystems
/proc/partitionsPartition information
/proc/swapsSwap space utilization
/proc/sys/Kernel tunable parameters
/proc/net/Network status information

/sys

Directory/FileDescription
/sys/class/Information about device classes
/sys/block/Information about block devices
/sys/fs/Filesystem information
/sys/kernel/Kernel information and tunable parameters
/sys/module/Information about loaded kernel modules
/sys/devices/Information about devices

/dev

Directory/FileDescription
/dev/sdaFirst SCSI disk drive
/dev/sdbSecond SCSI disk drive
/dev/ttyTerminal devices
/dev/nullNull device (discard output)
/dev/randomRandom number generator
/dev/urandomNon-blocking random number generator

Vim Cheatsheet

CommandDescription
iEnter insert mode
EscExit insert mode
:wSave the file
:qQuit Vim
:wqSave and quit Vim
:q!Quit without saving
:e filenameOpen a file
:nOpen the next file
:pOpen the previous file
/patternSearch for a pattern
nRepeat the last search
NRepeat the last search in the opposite direction
:s/old/new/gReplace all occurrences of old with new in the current line
:%s/old/new/gReplace all occurrences of old with new in the file
yyYank (copy) the current line
pPaste the yanked text
ddDelete the current line
uUndo the last action
Ctrl-rRedo the last undone action
ggGo to the first line of the file
GGo to the last line of the file
0Go to the beginning of the line
$Go to the end of the line
dGDelete from the current line to the end of the file
vEnter visual mode
VEnter visual line mode
Ctrl-vEnter visual block mode
:helpOpen Vim help
:!commandExecute an external command
:r !commandRead the output of a command into the current file
:set numberShow line numbers
:set nonumberHide line numbers
:syntax onEnable syntax highlighting
:syntax offDisable syntax highlighting

tmux Cheatsheet

CommandDescription
tmux new -s session_nameCreate a new session named session_name
tmux attach -t session_nameAttach to an existing session named session_name
tmux list-sessionsList all sessions
tmux kill-session -t session_nameKill the session named session_name
tmux new-window -n window_nameCreate a new window named window_name
tmux split-window -hSplit the current window horizontally
tmux split-window -vSplit the current window vertically
tmux select-pane -t :0Select pane 0
tmux resize-pane -LResize the current pane to the left
tmux resize-pane -RResize the current pane to the right
tmux resize-pane -UResize the current pane upwards
tmux resize-pane -DResize the current pane downwards
tmux kill-pane -t pane_numberKill the pane with the specified pane_number
tmux list-windowsList all windows in the current session
tmux kill-window -t window_numberKill the window with the specified window_number
tmux rename-window new_nameRename the current window to new_name
tmux list-panesList all panes in the current window
tmux swap-pane -s pane1 -t pane2Swap the position of pane1 and pane2
tmux move-pane -t target_paneMove the current pane to target_pane
tmux set-option -g prefix C-aChange the prefix key to Ctrl-a
tmux bind-key [key] [command]Bind a key to a tmux command
tmux unbind-key [key]Unbind a key from a tmux command
tmux source-file ~/.tmux.confReload the tmux configuration file
tmux save-buffer ~/buffer.txtSave the tmux paste buffer to a file
tmux show-options -gShow all global options
tmux display-message "message"Display a message in the status line
tmux clock-modeEnter clock mode in the current pane
tmux list-keysList all key bindings
tmux capture-pane -S -100Capture the last 100 lines of the current pane
tmux show-environmentShow the tmux environment variables
tmux detach-client -t session_nameDetach the client from session_name
tmux rename-session new_session_nameRename the current session to new_session_name
tmux rotate-window -URotate the current window upwards
tmux rotate-window -DRotate the current window downwards
tmux list-clientsList all clients
tmux select-layout even-horizontalArrange panes in an even horizontal layout
tmux select-layout even-verticalArrange panes in an even vertical layout
tmux select-layout tiledArrange panes in a tiled layout

tmux Hotkeys Cheatsheet

HotkeyDescription
Ctrl-bDefault prefix key (can be changed)
Ctrl-b ?List all key bindings
Ctrl-b dDetach from the current session
Ctrl-b cCreate a new window
Ctrl-b ,Rename the current window
Ctrl-b wList all windows
Ctrl-b nMove to the next window
Ctrl-b pMove to the previous window
Ctrl-b lMove to the last (previously active) window
Ctrl-b &Kill the current window
Ctrl-b %Split the current pane vertically
Ctrl-b "Split the current pane horizontally
Ctrl-b xKill the current pane
Ctrl-b oSwitch to the next pane
Ctrl-b ;Switch to the last active pane
Ctrl-b qDisplay pane numbers
Ctrl-b zToggle pane zoom
Ctrl-b {Swap pane with the previous pane
Ctrl-b }Swap pane with the next pane
Ctrl-b SpaceToggle through layouts
Ctrl-b Ctrl-oRotate panes
Ctrl-b tShow a clock
Ctrl-b mMark the current pane
Ctrl-b 'Prompt for an index to switch to
Ctrl-b !Break the current pane into a new window
Ctrl-b sList all sessions
Ctrl-b :Enter the tmux command prompt
Ctrl-b [Enter copy mode (scrollback buffer)
Ctrl-b ]Paste the buffer
Ctrl-b -Split the window vertically
Ctrl-b =Split the window horizontally
Ctrl-b fFind window by text
Ctrl-b rReload tmux configuration

SSH Cheatsheet

CommandDescription
ssh user@hostConnect to a remote host
ssh -p port user@hostConnect to a remote host on a specific port
ssh -i keyfile user@hostConnect using a specific private key file
ssh-copy-id user@hostCopy your public key to a remote host
ssh-keygen -t rsa -b 4096Generate a new RSA key pair
ssh-add keyfileAdd a private key to the SSH agent
ssh-agent bashStart the SSH agent
scp source user@host:destinationCopy files to a remote host
scp user@host:source destinationCopy files from a remote host
rsync -avz source user@host:destinationSync files to a remote host
rsync -avz user@host:source destinationSync files from a remote host
ssh user@host commandExecute a command on a remote host
ssh -L local_port:remote_host:remote_port user@hostCreate an SSH tunnel (local forwarding)
ssh -R remote_port:local_host:local_port user@hostCreate an SSH tunnel (remote forwarding)
ssh -D local_port user@hostCreate a dynamic SOCKS proxy
~.Terminate the SSH session
~COpen command line interface during an SSH session
~&Background the SSH session
ssh -X user@hostEnable X11 forwarding
ssh -v user@hostVerbose mode (debugging)
ssh -vv user@hostMore verbose mode
ssh -q user@hostQuiet mode (suppress warnings)
ssh -f user@host commandRun SSH in the background
ssh -N user@hostDo not execute a remote command
ssh -o option=value user@hostSet an option for the SSH connection
ssh -c cipher user@hostSpecify the cipher to use
ssh-keyscan hostRetrieve SSH public keys from a host
sshfs user@host:remote_dir local_dirMount a remote directory over SSH

Git Cheatsheet

CommandDescription
git initInitialize a new Git repository
git clone repository_urlClone an existing repository
git statusShow the status of the working directory
git add fileStage changes for commit
git commit -m "message"Commit staged changes with a message
git push origin branchPush commits to the remote repository
git pull origin branchPull updates from the remote repository
git fetchFetch changes from the remote repository
git merge branchMerge a branch into the current branch
git branchList all branches
git branch branch_nameCreate a new branch
git checkout branch_nameSwitch to a different branch
git checkout -b branch_nameCreate and switch to a new branch
git logShow commit history
git log --onelineShow commit history in a condensed form
git diffShow changes between commits, commit and working tree, etc
git reset --hard commitReset the working directory and index to a specific commit
git revert commitRevert a specific commit
git stashStash changes in a dirty working directory
git stash popApply stashed changes
git remote -vShow remote repositories
git remote add name urlAdd a remote repository
git tagList tags
git tag tag_nameCreate a new tag
git rm fileRemove a file from the working directory and index
git mv old_name new_nameRename or move a file
git blame fileShow what revision and author last modified each line
git show commitShow various types of objects
git config --global user.name "name"Set the global username
git config --global user.email "email"Set the global email
git rebase branchReapply commits on top of another base tip
git cherry-pick commitApply changes from a specific commit
git bisect startStart binary search to find the commit that introduced a bug
git archive --format zip --output file.zip HEADCreate a zip archive of the current branch
git gcCleanup unnecessary files and optimize the local repository

Systemd Cheatsheet

CommandDescription
systemctl start serviceStart a service
systemctl stop serviceStop a service
systemctl restart serviceRestart a service
systemctl reload serviceReload a service's configuration
systemctl enable serviceEnable a service to start on boot
systemctl disable serviceDisable a service from starting on boot
systemctl status serviceShow the status of a service
systemctl is-active serviceCheck if a service is active
systemctl is-enabled serviceCheck if a service is enabled
systemctl list-unitsList all loaded units
systemctl list-unit-filesList installed unit files
systemctl daemon-reloadReload systemd manager configuration
journalctl -u serviceView logs for a specific service
journalctl -fFollow the system journal
systemctl mask serviceMask a service to prevent it from being started
systemctl unmask serviceUnmask a service
systemctl set-default targetSet the default target (e.g., multi-user, graphical)
systemctl get-defaultGet the current default target
systemctl isolate targetChange to a different target
systemctl show serviceShow properties of a unit
systemctl cat serviceShow the unit file of a service
systemctl edit serviceEdit a unit file (creates an override file)
systemctl reset-failed serviceReset the failed state of a unit
systemctl poweroffPower off the system
systemctl rebootReboot the system
systemctl suspendSuspend the system
systemctl hibernateHibernate the system
systemctl hybrid-sleepHibernate and suspend the system
systemd-analyze blameShow the time taken to initialize each service
systemd-analyze critical-chainShow the critical chain of units
systemd-analyze plot > plot.svgGenerate a graphical representation of the boot process
timedatectlControl the system time and date
hostnamectlControl the system hostname
localectlControl the system locale
loginctlControl the system logind

Docker Cheatsheet

CommandDescription
docker psList running containers
docker ps -aList all containers
docker imagesList all images
docker pull imagePull an image from a registry
docker run imageRun a container from an image
docker run -d imageRun a container in detached mode
docker run -it imageRun a container in interactive mode
docker stop containerStop a running container
docker start containerStart a stopped container
docker restart containerRestart a container
docker rm containerRemove a container
docker rmi imageRemove an image
docker exec -it container bashExecute a command in a running container
docker logs containerView logs of a container
docker build -t image .Build an image from a Dockerfile
docker-compose upStart containers defined in docker-compose.yml
docker-compose downStop and remove containers defined in docker-compose.yml
docker network lsList all networks
docker network create networkCreate a new network
docker volume lsList all volumes
docker volume create volumeCreate a new volume
docker inspect containerDisplay detailed information on a container
docker tag source_image target_imageTag an image
docker push imagePush an image to a registry
docker pull imagePull an image from a registry
docker save -o image.tar imageSave an image to a tar file
docker load -i image.tarLoad an image from a tar file
docker stats containerDisplay resource usage statistics of a container
docker top containerDisplay the running processes of a container
docker cp source_path container:dest_pathCopy files/folders between a container and the local filesystem
docker update --cpus=2 containerUpdate resource limits of a container
docker history imageShow the history of an image
docker diff containerInspect changes to files or directories on a container’s filesystem
docker export container -o container.tarExport a container’s filesystem to a tar archive
docker import file.tarImport a tarball to create a filesystem image

Kubernetes Cheatsheet

CommandDescription
kubectl get nodesList all nodes
kubectl get podsList all pods in the default namespace
kubectl get pods -n namespaceList all pods in a specific namespace
kubectl get servicesList all services in the default namespace
kubectl describe pod pod_nameShow detailed information about a specific pod
kubectl logs pod_namePrint the logs of a specific pod
kubectl exec -it pod_name -- bashExecute a command in a running pod
kubectl apply -f file.yamlApply a configuration file
kubectl create -f file.yamlCreate resources from a configuration file
kubectl delete -f file.yamlDelete resources defined in a configuration file
kubectl scale --replicas=3 deployment/appScale a deployment to 3 replicas
kubectl rollout status deployment/appCheck the rollout status of a deployment
kubectl rollout undo deployment/appRoll back a deployment
kubectl expose deployment app --type=LoadBalancer --port=80Expose a deployment as a service
kubectl port-forward pod_name 8080:80Forward a local port to a port on a pod
kubectl get namespacesList all namespaces
kubectl create namespace namespaceCreate a new namespace
kubectl config set-context --current --namespace=namespaceSet the current namespace
kubectl get eventsList all events
kubectl get secretsList all secrets in the default namespace
kubectl get configmapsList all configmaps in the default namespace
kubectl describe node node_nameShow detailed information about a specific node
kubectl get deploymentList all deployments in the default namespace
kubectl describe service service_nameShow detailed information about a specific service
kubectl set image deployment/app app=nginx:1.16Update the image of a deployment
kubectl edit deployment appEdit a resource on the server
kubectl delete pod pod_nameDelete a specific pod
kubectl delete service service_nameDelete a specific service
kubectl apply -f https://k8s.io/examples/application/deployment.yamlApply a deployment from a URL
kubectl get pvcList all persistent volume claims
kubectl get pvList all persistent volumes
kubectl cordon node_nameMark a node as unschedulable
kubectl drain node_nameDrain a node by evicting all pods
kubectl taint nodes node_name key=value:NoScheduleTaint a node to prevent scheduling

Ansible Cheatsheet

CommandDescription
ansible all -m pingPing all hosts
ansible-playbook playbook.yamlRun a playbook
ansible all -a "command"Run a command on all hosts
ansible all -m setupGather facts from all hosts
ansible all -m yum -a "name=package state=present"Install a package using yum
ansible all -m copy -a "src=/local/path dest=/remote/path"Copy files to remote hosts
ansible-vault create secret.yamlCreate an encrypted file
ansible-vault edit secret.yamlEdit an encrypted file
ansible-vault decrypt secret.yamlDecrypt an encrypted file
ansible-playbook --ask-vault-password playbook.yamlRun a playbook with vault password
ansible-galaxy install role_nameInstall a role from Ansible Galaxy
ansible-galaxy listList installed roles
ansible-doc -lList all modules
ansible-doc module_nameShow documentation for a specific module
ansible-playbook -i inventory playbook.yamlRun a playbook with a specific inventory
ansible all -m service -a "name=service state=started"Manage services on remote hosts
ansible all -m file -a "path=/remote/path state=directory"Ensure a directory exists on remote hosts
ansible all -m user -a "name=username state=present"Ensure a user exists on remote hosts
ansible-playbook --check playbook.yamlRun a playbook in check mode
ansible-playbook --diff playbook.yamlShow changes made by the playbook
ansible-playbook -e "variable=value" playbook.yamlPass extra variables to the playbook
ansible-playbook --tags "tag_name" playbook.yamlRun playbook tasks with specific tags
ansible-inventory --list -i inventoryList inventory hosts
ansible-inventory --graph -i inventoryShow inventory graph
ansible-config dumpDump the Ansible configuration
ansible-config listList all Ansible configuration options
ansible-pull -U repo_urlPull and run a playbook from a remote Git repository
ansible-playbook --limit "host_pattern" playbook.yamlLimit playbook run to specific hosts
ansible-playbook --start-at-task "task_name" playbook.yamlStart playbook run at a specific task
ansible-galaxy init role_nameInitialize a new role

iptables Cheatsheet

CommandDescription
iptables -LList all rules
iptables -A chain -j targetAppend a rule to a chain
iptables -I chain rule_num -j targetInsert a rule at a specific position in a chain
iptables -D chain rule_numDelete a rule from a chain by number
iptables -FFlush all rules
iptables -XDelete all user-defined chains
iptables -P chain targetSet the default policy for a chain
iptables -N chainCreate a new user-defined chain
iptables -A INPUT -p tcp --dport port -j ACCEPTAllow incoming TCP traffic on a specific port
iptables -A OUTPUT -p tcp --sport port -j ACCEPTAllow outgoing TCP traffic on a specific port
iptables -A FORWARD -i interface -j ACCEPTAllow forwarding from a specific interface
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPTAllow established and related connections
iptables -A INPUT -s ip_address -j DROPBlock traffic from a specific IP address
iptables -A INPUT -p icmp -j ACCEPTAllow ICMP (ping) traffic
iptables -A INPUT -p udp --dport port -j ACCEPTAllow incoming UDP traffic on a specific port
iptables -A INPUT -p tcp --dport 22 -j ACCEPTAllow SSH traffic
iptables -A INPUT -j REJECTReject all other incoming traffic
iptables-save > /etc/iptables/rules.v4Save the current rules to a file
iptables-restore < /etc/iptables/rules.v4Restore rules from a file

nftables Cheatsheet

CommandDescription
nft list rulesetList all rulesets
nft add table inet filterCreate a new table
nft add chain inet filter input { type filter hook input priority 0; }Create a new chain
nft add rule inet filter input ip saddr ip_address dropDrop traffic from a specific IP address
nft add rule inet filter input tcp dport port acceptAllow incoming TCP traffic on a specific port
nft add rule inet filter input udp dport port acceptAllow incoming UDP traffic on a specific port
nft add rule inet filter input icmp type echo-request acceptAllow ICMP (ping) traffic
nft add rule inet filter input ct state established,related acceptAllow established and related connections
nft add rule inet filter input iifname interface acceptAllow traffic from a specific interface
nft add rule inet filter output tcp sport port acceptAllow outgoing TCP traffic on a specific port
nft add rule inet filter forward iifname interface oifname interface acceptAllow forwarding between interfaces
nft delete rule inet filter input handle handle_numberDelete a specific rule by handle number
nft delete chain inet filter inputDelete a chain
nft delete table inet filterDelete a table
nft -f /etc/nftables.confLoad rules from a configuration file
nft save > /etc/nftables.confSave the current ruleset to a file
nft -i /etc/nftables.confLoad rules from a file interactively
nft monitorMonitor changes to the ruleset
nft add set inet filter blacklist { type ipv4_addr; }Create an IP set
nft add element inet filter blacklist { ip_address }Add an IP address to the set
nft delete element inet filter blacklist { ip_address }Remove an IP address from the set
nft add rule inet filter input ip saddr @blacklist dropDrop traffic from IP addresses in the set

Cron Cheatsheet

CommandDescription
crontab -eEdit the current user's crontab
crontab -lList the current user's crontab
crontab -rRemove the current user's crontab
crontab -u user -eEdit another user's crontab
crontab -u user -lList another user's crontab
crontab -u user -rRemove another user's crontab
@reboot commandRun once at startup
@yearly commandRun once a year (0 0 1 1 *)
@annually commandRun once a year (0 0 1 1 *)
@monthly commandRun once a month (0 0 1 * *)
@weekly commandRun once a week (0 0 * * 0)
@daily commandRun once a day (0 0 * * *)
@midnight commandRun once a day (0 0 * * *)
@hourly commandRun once an hour (0 * * * *)
* * * * * commandRun every minute
*/5 * * * * commandRun every 5 minutes
0 * * * * commandRun at the beginning of every hour
0 0 * * * commandRun at midnight every day
0 0 1 * * commandRun at midnight on the first of every month
0 0 1 1 * commandRun at midnight on January 1st
0 9 * * 1-5 commandRun at 9 AM on weekdays
0 22 * * 1-5 commandRun at 10 PM on weekdays
MAILTO="email@example.com"Send cron job output to the specified email address
0 0 * * * /path/to/script.shRun a script daily at midnight
0 5 * * * /path/to/backup.shRun a backup script daily at 5 AM
*/10 * * * * /path/to/check.shRun a script every 10 minutes
0 0 * * 0 /path/to/weekly.shRun a script weekly on Sundays at midnight
0 0 1 * * /path/to/monthly.shRun a script monthly on the first day at midnight
0 0 1 1 * /path/to/yearly.shRun a script yearly on January 1st at midnight

awk Cheatsheet

CommandDescription
awk '{print}' filePrint all lines in a file
awk '{print $1}' filePrint the first field of each line
awk '{print $1, $2}' filePrint the first and second fields of each line
awk '/pattern/ {print}' filePrint lines matching a pattern
awk 'NR==line_number' filePrint a specific line number
awk 'NR==start, NR==end' filePrint a range of lines
awk '{sum += $1} END {print sum}' fileSum the first field of all lines
awk 'BEGIN {print "Header"} {print} END {print "Footer"}' fileAdd a header and footer to the output
awk -F, '{print $1}' fileSpecify a field separator (comma in this case)
awk '{if ($1 > 10) print}' filePrint lines where the first field is greater than 10
awk '{gsub(/old/, "new"); print}' fileReplace all occurrences of "old" with "new"
awk '{print NR, $0}' filePrint line numbers with output
awk '{print length($0)}' filePrint the length of each line
awk '{print $NF}' filePrint the last field of each line
awk '{print $(NF-1)}' filePrint the second to last field of each line
awk '{count[$1]++} END {for (word in count) print word, count[word]}' fileCount occurrences of each word in the first field
awk 'NR % 2 == 0 {print}' filePrint every second line
awk '{print toupper($0)}' fileConvert text to uppercase
awk '{print tolower($0)}' fileConvert text to lowercase
awk 'BEGIN {FS=":"; OFS="-"} {print $1, $2}' fileChange input and output field separators

sed Cheatsheet

CommandDescription
sed 's/old/new/' fileReplace the first occurrence of "old" with "new"
sed 's/old/new/g' fileReplace all occurrences of "old" with "new"
sed -i 's/old/new/g' fileReplace all occurrences in the file (in-place)
sed 's/old/new/2' fileReplace the second occurrence of "old" with "new"
sed 's/old/new/gi' fileReplace all occurrences, case insensitive
sed '1,3s/old/new/' fileReplace occurrences between lines 1 and 3
sed '3s/old/new/' fileReplace occurrences on the third line
sed '/pattern/s/old/new/' fileReplace occurrences on lines matching a pattern
sed 's/^/prefix/' fileAdd a prefix to each line
sed 's/$/suffix/' fileAdd a suffix to each line
sed '/pattern/d' fileDelete lines matching a pattern
sed '3d' fileDelete the third line
sed '1,3d' fileDelete lines 1 through 3
sed '$d' fileDelete the last line
sed -n '2,4p' filePrint lines 2 through 4
sed -n '/pattern/p' filePrint lines matching a pattern
sed -e 'command1' -e 'command2' fileApply multiple commands
sed 's/.*\(pattern\).*/\1/' fileExtract and print a pattern
sed 'y/abc/ABC/' fileTranslate characters
sed -i.bak 's/old/new/g' fileReplace all occurrences and create a backup file
sed '10q' fileQuit after 10 lines
sed 's/\([0-9]\{3\}\)-\([0-9]\{2\}\)-\([0-9]\{4\}\)/\1\2\3/' fileRemove dashes from SSN format
sed 's/ *$//' fileRemove trailing whitespace
sed 's/[^[:alnum:]]//g' fileRemove all non-alphanumeric characters

grep Cheatsheet

CommandDescription
grep "pattern" fileSearch for a pattern in a file
grep -i "pattern" fileCase-insensitive search
grep -v "pattern" fileInvert match, show lines that do not match
grep -r "pattern" directoryRecursively search in a directory
grep -l "pattern" fileShow file names containing the pattern
grep -c "pattern" fileCount occurrences of the pattern
grep -n "pattern" fileShow line numbers of matches
grep -w "pattern" fileMatch whole words only
grep -A num "pattern" fileShow num lines after match
grep -B num "pattern" fileShow num lines before match
grep -C num "pattern" fileShow num lines around match
grep -e "pattern1" -e "pattern2" fileSearch for multiple patterns
grep --exclude=*.txt "pattern" *Exclude files matching a pattern
grep --include=*.txt "pattern" *Include only files matching a pattern
grep -f patternfile fileUse patterns from a file
grep -q "pattern" fileQuiet mode, return 0 if pattern is found
grep --color=auto "pattern" fileHighlight matches in color
grep -o "pattern" filePrint only matching parts of a line
grep --line-buffered "pattern" fileUse line buffering (useful for streaming)

find Cheatsheet

CommandDescription
find . -name "filename"Find files by name
find . -iname "filename"Find files by name (case-insensitive)
find . -type d -name "dirname"Find directories by name
find . -type f -name "filename"Find regular files by name
find . -size +1MFind files larger than 1MB
find . -size -1MFind files smaller than 1MB
find . -mtime -1Find files modified in the last day
find . -atime -1Find files accessed in the last day
find . -user usernameFind files owned by a specific user
find . -group groupnameFind files owned by a specific group
find . -perm 644Find files with specific permissions
find . -exec command {} \;Execute a command on each file found
find . -exec rm {} \;Delete all files found
find . -printPrint the full file names
find . -maxdepth 1 -name "filename"Find files in the current directory only
find . -mindepth 2 -name "filename"Find files not in the top-level directory
find . -type lFind symbolic links
find . -type l -xtype fFind broken symbolic links
find . -emptyFind empty files and directories
find . -newer fileFind files newer than a specific file
find . -name "*.txt" -or -name "*.md"Find files matching multiple patterns
find . -path "./dir/*" -prune -o -name "*.txt" -printExclude a directory and find files
find . -ctime +10Find files changed more than 10 days ago
find . -cmin -60Find files changed in the last 60 minutes
find / -type f 2>/dev/nullFind all files on the system, ignoring permission errors

Screen Cheatsheet

CommandDescription
screenStart a new screen session
screen -S session_nameStart a new session named session_name
screen -lsList all screen sessions
screen -r session_nameResume a detached session named session_name
screen -d -r session_nameDetach and reattach to session_name
screen -X -S session_name quitKill a session named session_name
Ctrl-a dDetach from the current session
Ctrl-a cCreate a new window
Ctrl-a "List all windows
Ctrl-a 0Switch to window 0
Ctrl-a ARename the current window
Ctrl-a nSwitch to the next window
Ctrl-a pSwitch to the previous window
Ctrl-a kKill the current window
Ctrl-a Ctrl-aSwitch between the current and previous window
Ctrl-a SSplit the screen horizontally
Ctrl-a \|Split the screen vertically
Ctrl-a tabSwitch to the next region
Ctrl-a XClose the current region
Ctrl-a QClose all regions except the current one
Ctrl-a spaceToggle between layouts
Ctrl-a :resizeResize the current region
Ctrl-a :fitFit the current region to the screen
Ctrl-a [ Enter copy mode
Ctrl-a ] Paste copied text
Ctrl-a ? Show key bindings help
Ctrl-a H Begin/end logging of the session
Ctrl-a _ Lock the terminal
Ctrl-a m Monitor the current window for activity
Ctrl-a M Monitor the current window for silence
Ctrl-a D DDetach and logout from the session

rsync Cheatsheet

CommandDescription
rsync -av source destinationArchive mode, verbose
rsync -avz source destinationArchive mode, compress during transfer
rsync -av --progress source destinationShow progress during transfer
rsync -av --delete source destinationDelete extraneous files from destination
rsync -av --exclude='pattern' source destinationExclude files matching a pattern
rsync -av --include='pattern' source destinationInclude only files matching a pattern
rsync -av -e ssh source user@host:destinationUse SSH as the transport
rsync -av --dry-run source destinationPerform a trial run with no changes made
rsync -av --partial source destinationKeep partially transferred files
rsync -av --bwlimit=KBps source destinationLimit bandwidth during transfer
rsync -av --size-only source destinationSkip files that match in size
rsync -av --checksum source destinationSkip files that match in checksum
rsync -av --times source destinationPreserve modification times
rsync -av --perms source destinationPreserve permissions
rsync -av --owner source destinationPreserve owner
rsync -av --group source destinationPreserve group
rsync -av --links source destinationCopy symlinks as symlinks
rsync -av --hard-links source destinationPreserve hard links
rsync -av --copy-links source destinationCopy symlinks as files
rsync -av --copy-dirlinks source destinationTransform symlinks to directories into real dirs
rsync -av --no-links source destinationSkip copying symlinks
rsync -av --safe-links source destinationIgnore symlinks that point outside source tree
rsync -av --delete-excluded source destinationDelete excluded files from destination
rsync -av --max-size=SIZE source destinationLimit maximum size of files to transfer
rsync -av --min-size=SIZE source destinationLimit minimum size of files to transfer
rsync -av --backup source destinationBackup files that are replaced
rsync -av --backup-dir=DIR source destinationBackup files into a specific directory
rsync -av --suffix=SUFFIX source destinationDefine suffix for backup files
rsync -av --inplace source destinationUpdate destination files in place
rsync -av --append source destinationAppend data onto shorter files
rsync -av --append-verify source destinationAppend and verify full file content
rsync -av --ignore-existing source destinationSkip updating files that already exist
rsync -av --remove-source-files source destinationRemove source files after transfer

tar Cheatsheet

CommandDescription
tar -cvf archive.tar file_or_directoryCreate a tar archive
tar -xvf archive.tarExtract a tar archive
tar -tvf archive.tarList contents of a tar archive
tar -cvzf archive.tar.gz file_or_directoryCreate a gzip-compressed tar archive
tar -xvzf archive.tar.gzExtract a gzip-compressed tar archive
tar -cvjf archive.tar.bz2 file_or_directoryCreate a bzip2-compressed tar archive
tar -xvjf archive.tar.bz2Extract a bzip2-compressed tar archive
tar -cvJf archive.tar.xz file_or_directoryCreate a xz-compressed tar archive
tar -xvJf archive.tar.xzExtract a xz-compressed tar archive
tar -cvf - file_or_directory \| ssh user@host "tar -xvf - -C /destination"Copy files over SSH
tar -rf archive.tar fileAppend files to an existing tar archive
tar -uf archive.tar fileUpdate files in an existing tar archive
tar -cvf archive.tar --exclude="*.txt" file_or_directoryCreate tar archive excluding certain files
tar -cvf archive.tar --exclude-vcs file_or_directoryCreate tar archive excluding version control files
tar --delete -f archive.tar fileDelete files from a tar archive
tar -cvf archive.tar -T filelist.txtCreate tar archive from a list of files
tar -xvf archive.tar -C /destinationExtract tar archive to a specific directory
tar --strip-components=number -xvf archive.tarExtract tar archive, removing a number of leading components
tar --transform='s/old/new/' -cvf archive.tar file_or_directoryCreate tar archive with transformed file names
tar -xzvf archive.tar.gz --wildcards '*.txt'Extract specific files from a compressed tar archive

gzip Cheatsheet

CommandDescription
gzip fileCompress a file
gzip -d file.gzDecompress a file
gzip -k fileCompress a file, keeping the original
gzip -r directoryRecursively compress files in a directory
gzip -l file.gzList compressed file details
gzip -t file.gzTest compressed file integrity
gzip -v fileCompress a file with verbose output
gzip -1 fileCompress a file with fastest speed
gzip -9 fileCompress a file with best compression
zcat file.gzView contents of a compressed file
zgrep "pattern" file.gzSearch for a pattern in a compressed file
zless file.gzView a compressed file with less
zcmp file1.gz file2.gzCompare compressed files
zdiff file1.gz file2.gzShow differences between compressed files

bzip2 Cheatsheet

CommandDescription
bzip2 fileCompress a file
bzip2 -d file.bz2Decompress a file
bzip2 -k fileCompress a file, keeping the original
bzip2 -z fileCompress a file
bzip2 -t file.bz2Test compressed file integrity
bzip2 -c file > file.bz2Compress a file to standard output
bzip2 -f fileForce compression or decompression
bzip2 -v fileCompress a file with verbose output
bzip2 -1 fileCompress a file with fastest speed
bzip2 -9 fileCompress a file with best compression
bzcat file.bz2View contents of a compressed file
bzgrep "pattern" file.bz2Search for a pattern in a compressed file
bzless file.bz2View a compressed file with less
bzcmp file1.bz2 file2.bz2Compare compressed files
bzdiff file1.bz2 file2.bz2Show differences between compressed files

curl Cheatsheet

CommandDescription
curl urlFetch the content of a URL
curl -o file urlSave the content to a file
curl -O urlSave the content to a file with the same name
curl -L urlFollow redirects
curl -I urlFetch headers only
curl -d "data" urlSend data with a POST request
curl -X POST urlSend a POST request
curl -X PUT urlSend a PUT request
curl -X DELETE urlSend a DELETE request
curl -H "Header: value" urlSend a custom header
curl -u user:password urlSend basic authentication
curl -F "name=value" urlSend a multipart form data
curl -k urlAllow insecure SSL connections
curl --cert certfile urlSend a client certificate
curl -b "name=value" urlSend cookies
curl -c cookiefile urlSave cookies to a file
curl --limit-rate 100k urlLimit the transfer rate
curl --compressed urlRequest a compressed response
curl --retry num urlRetry a request on failure
curl --silent urlSilent mode (suppress output)
curl --progress-bar urlDisplay a progress bar
curl --http2 urlUse HTTP/2 protocol
curl --interface interface urlUse a specific network interface
curl --ipv4 urlUse IPv4 only
curl --ipv6 urlUse IPv6 only
curl --location-trusted urlFollow redirects and send authentication to other hosts
curl --data-urlencode "name=value" urlURL encode data
curl --max-time seconds urlSet a maximum time for the request
curl --connect-timeout seconds urlSet a maximum time for the connection
curl --proxy proxy_url urlUse a proxy server

wget Cheatsheet

CommandDescription
wget urlDownload a file
wget -O file urlSave the download with a specific name
wget -P /path urlSave the download to a specific directory
wget -c urlContinue a partially downloaded file
wget -b urlDownload in the background
wget -i fileDownload URLs listed in a file
wget -r urlDownload recursively
wget -l depth urlSet the download depth
wget -k urlConvert links to be suitable for local viewing
wget -m urlMirror a website
wget -p urlDownload all necessary files to display a webpage
wget --limit-rate=100k urlLimit the download speed
wget --user=user --password=password urlDownload with basic authentication
wget --header="Header: value" urlSend a custom header
wget --no-check-certificate urlIgnore SSL certificate errors
wget --quiet urlQuiet mode (no output)
wget --show-progress urlShow a progress bar
wget --spider urlCheck if a URL exists
wget --no-clobber urlDo not overwrite existing files
wget --timestamping urlDownload only if the remote file is newer than the local file
wget --directory-prefix=prefix urlSave files to a specific directory
wget --tries=num urlSet the number of retries
wget --wait=seconds urlWait between downloads
wget --random-wait urlWait a random amount of time between downloads
wget --delete-after urlDelete files after downloading
wget --mirror urlMirror a website
wget --recursive urlDownload files recursively
wget --level=depth urlSet the recursion depth
wget --user-agent="User-Agent" urlSet the user agent

MySQL/MariaDB Cheatsheet

CommandDescription
mysql -u user -pConnect to the MySQL server
CREATE DATABASE dbname;Create a new database
DROP DATABASE dbname;Delete a database
USE dbname;Select a database
SHOW DATABASES;List all databases
SHOW TABLES;List all tables in the selected database
DESCRIBE tablename;Show table structure
CREATE TABLE tablename (columns);Create a new table
DROP TABLE tablename;Delete a table
INSERT INTO tablename (columns) VALUES (values);Insert data into a table
SELECT * FROM tablename;Retrieve all data from a table
UPDATE tablename SET column=value WHERE condition;Update data in a table
DELETE FROM tablename WHERE condition;Delete data from a table
GRANT ALL PRIVILEGES ON dbname.* TO 'user'@'host' IDENTIFIED BY 'password';Grant privileges to a user
FLUSH PRIVILEGES;Reload privileges
SHOW GRANTS FOR 'user'@'host';Show granted privileges
REVOKE ALL PRIVILEGES ON dbname.* FROM 'user'@'host';Revoke privileges from a user
CREATE USER 'user'@'host' IDENTIFIED BY 'password';Create a new user
DROP USER 'user'@'host';Delete a user
SHOW PROCESSLIST;Show running processes
EXIT;Exit the MySQL shell
mysqldump -u user -p dbname > backup.sqlBackup a database
mysql -u user -p dbname < backup.sqlRestore a database
SHOW STATUS;Show server status
SHOW VARIABLES;Show server variables
SHOW INDEX FROM tablename;Show indexes in a table
SHOW CREATE TABLE tablename;Show the CREATE TABLE statement for a table
ALTER TABLE tablename ADD columnname datatype;Add a column to a table
ALTER TABLE tablename DROP columnname;Drop a column from a table
ALTER TABLE tablename MODIFY columnname datatype;Modify a column in a table
ALTER TABLE tablename RENAME TO newtablename;Rename a table
CREATE INDEX indexname ON tablename (columns);Create an index on a table
DROP INDEX indexname ON tablename;Drop an index from a table
SET GLOBAL max_connections = value;Set a global variable
SHOW ENGINE INNODB STATUS;Show InnoDB status

PostgreSQL Cheatsheet

CommandDescription
psql -U user -d dbnameConnect to the PostgreSQL server
CREATE DATABASE dbname;Create a new database
DROP DATABASE dbname;Delete a database
\c dbnameConnect to a database
\lList all databases
\dtList all tables in the connected database
\d tablenameShow table structure
CREATE TABLE tablename (columns);Create a new table
DROP TABLE tablename;Delete a table
INSERT INTO tablename (columns) VALUES (values);Insert data into a table
SELECT * FROM tablename;Retrieve all data from a table
UPDATE tablename SET column=value WHERE condition;Update data in a table
DELETE FROM tablename WHERE condition;Delete data from a table
GRANT ALL PRIVILEGES ON DATABASE dbname TO user;Grant privileges to a user
REVOKE ALL PRIVILEGES ON DATABASE dbname FROM user;Revoke privileges from a user
CREATE USER username WITH PASSWORD 'password';Create a new user
DROP USER username;Delete a user
\qExit the PostgreSQL shell
pg_dump -U user -d dbname -f backup.sqlBackup a database
psql -U user -d dbname -f backup.sqlRestore a database
\conninfoShow connection information
\duList all roles
\diList all indexes
\dfList all functions
\dnList all schemas
\dpList table, view, and sequence access privileges
ALTER TABLE tablename ADD columnname datatype;Add a column to a table
ALTER TABLE tablename DROP columnname;Drop a column from a table
ALTER TABLE tablename ALTER COLUMN columnname TYPE datatype;Modify a column in a table
ALTER TABLE tablename RENAME TO newtablename;Rename a table
CREATE INDEX indexname ON tablename (columns);Create an index on a table
DROP INDEX indexname;Drop an index
VACUUMClean up and optimize the database
VACUUM FULLClean up and optimize the database (full)
ANALYZECollect statistics about the database
EXPLAIN SELECT * FROM tablename;Show the execution plan for a query
SET search_path TO schema;Set the search path to a specific schema

Nginx Cheatsheet

CommandDescription
sudo systemctl start nginxStart Nginx
sudo systemctl stop nginxStop Nginx
sudo systemctl restart nginxRestart Nginx
sudo systemctl reload nginxReload Nginx configuration
sudo systemctl enable nginxEnable Nginx to start on boot
sudo systemctl disable nginxDisable Nginx from starting on boot
nginx -tTest Nginx configuration
nginx -s reloadReload Nginx configuration
nginx -s reopenReopen log files
nginx -s stopStop Nginx
nginx -s quitGracefully stop Nginx
/etc/nginx/nginx.confMain Nginx configuration file
/etc/nginx/sites-available/Directory for available site configurations
/etc/nginx/sites-enabled/Directory for enabled site configurations
sudo ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/Enable a site configuration
sudo unlink /etc/nginx/sites-enabled/siteDisable a site configuration
server { ... }Define a virtual server block
location / { ... }Define a location block
listen 80;Listen on port 80
listen 443 ssl;Listen on port 443 with SSL
server_name domain.com;Define the server name
root /var/www/html;Define the document root
index index.html;Define the default index file
error_page 404 /404.html;Define a custom error page
access_log /var/log/nginx/access.log;Define the access log file
error_log /var/log/nginx/error.log;Define the error log file
proxy_pass http://backend;Proxy requests to a backend server
rewrite ^/old/(.*)$ /new/$1 permanent;Rewrite URL
location ~ \.php$ { ... }Define a location block for PHP files
include /etc/nginx/conf.d/*.conf;Include additional configuration files
ssl_certificate /etc/nginx/ssl/nginx.crt;Define the SSL certificate
ssl_certificate_key /etc/nginx/ssl/nginx.key;Define the SSL certificate key
ssl_protocols TLSv1.2 TLSv1.3;Define the supported SSL protocols
ssl_ciphers HIGH:!aNULL:!MD5;Define the supported SSL ciphers

Apache Cheatsheet

CommandDescription
sudo systemctl start apache2Start Apache
sudo systemctl stop apache2Stop Apache
sudo systemctl restart apache2Restart Apache
sudo systemctl reload apache2Reload Apache configuration
sudo systemctl enable apache2Enable Apache to start on boot
sudo systemctl disable apache2Disable Apache from starting on boot
apachectl configtestTest Apache configuration
apachectl gracefulGracefully restart Apache
/etc/apache2/apache2.confMain Apache configuration file
/etc/apache2/sites-available/Directory for available site configurations
/etc/apache2/sites-enabled/Directory for enabled site configurations
sudo a2ensite siteEnable a site configuration
sudo a2dissite siteDisable a site configuration
sudo a2enmod moduleEnable a module
sudo a2dismod moduleDisable a module
sudo a2enconf configEnable a configuration
sudo a2disconf configDisable a configuration
<VirtualHost *:80> ... </VirtualHost>Define a virtual host for HTTP
<VirtualHost *:443> ... </VirtualHost>Define a virtual host for HTTPS
ServerName domain.comDefine the server name
DocumentRoot /var/www/htmlDefine the document root
DirectoryIndex index.htmlDefine the default index file
ErrorLog /var/log/apache2/error.logDefine the error log file
CustomLog /var/log/apache2/access.log combinedDefine the access log file
SSLEngine onEnable SSL
SSLCertificateFile /etc/apache2/ssl/apache.crtDefine the SSL certificate
SSLCertificateKeyFile /etc/apache2/ssl/apache.keyDefine the SSL certificate key
SSLProtocol all -SSLv2 -SSLv3Define the supported SSL protocols
SSLCipherSuite HIGH:!aNULL:!MD5Define the supported SSL ciphers
ProxyPass /app http://backend/appProxy requests to a backend server
ProxyPassReverse /app http://backend/appAdjust the URL in the Location header
RewriteEngine onEnable URL rewriting
RewriteRule ^/old/(.*)$ /new/$1 [R=301,L]Rewrite URL
<Directory /var/www/html> ... </Directory>Define directory-specific settings
Options Indexes FollowSymLinksSet directory options
AllowOverride AllAllow .htaccess to override settings
Require all grantedAllow access to a directory
Redirect permanent /old /newRedirect a URL

Firewalld Cheatsheet

CommandDescription
firewall-cmd --stateCheck the state of firewalld
firewall-cmd --reloadReload firewalld configuration
firewall-cmd --get-active-zonesList all active zones
firewall-cmd --get-default-zoneGet the default zone
firewall-cmd --zone=zone --list-allList all settings in a zone
firewall-cmd --zone=zone --add-source=sourceAdd a source to a zone
firewall-cmd --zone=zone --add-port=port/protocolAdd a port to a zone
firewall-cmd --zone=zone --remove-port=port/protocolRemove a port from a zone
firewall-cmd --zone=zone --add-service=serviceAdd a service to a zone
firewall-cmd --zone=zone --remove-service=serviceRemove a service from a zone
firewall-cmd --permanentApply changes permanently
firewall-cmd --runtime-to-permanentSave runtime changes to permanent configuration
firewall-cmd --add-masqueradeEnable masquerading (NAT)
firewall-cmd --remove-masqueradeDisable masquerading (NAT)
firewall-cmd --zone=zone --add-rich-rule='rule'Add a rich rule to a zone
firewall-cmd --zone=zone --remove-rich-rule='rule'Remove a rich rule from a zone

UFW Cheatsheet

CommandDescription
sudo ufw enableEnable UFW
sudo ufw disableDisable UFW
sudo ufw statusShow the current status of UFW and list rules
sudo ufw status verboseShow the current status of UFW with detailed information
sudo ufw allow portAllow incoming traffic on a specific port
sudo ufw allow from IPAllow incoming traffic from a specific IP address
sudo ufw allow from IP to any port portAllow incoming traffic from a specific IP to a specific port
sudo ufw allow proto tcp from IP to any port portAllow incoming TCP traffic from a specific IP to a specific port
sudo ufw deny portDeny incoming traffic on a specific port
sudo ufw deny from IPDeny incoming traffic from a specific IP address
sudo ufw deny from IP to any port portDeny incoming traffic from a specific IP to a specific port
sudo ufw delete allow portDelete an allow rule for a specific port
sudo ufw delete deny portDelete a deny rule for a specific port
sudo ufw default allow outgoingSet the default policy to allow outgoing traffic
sudo ufw default deny outgoingSet the default policy to deny outgoing traffic
sudo ufw default allow incomingSet the default policy to allow incoming traffic
sudo ufw default deny incomingSet the default policy to deny incoming traffic
sudo ufw resetReset UFW rules to the default state
sudo ufw show rawShow the raw iptables rules generated by UFW
sudo ufw logging onEnable logging for UFW
sudo ufw logging offDisable logging for UFW
sudo ufw logging lowSet logging level to low
sudo ufw logging mediumSet logging level to medium
sudo ufw logging highSet logging level to high
sudo ufw app listList all available application profiles
sudo ufw app info ApplicationShow information about a specific application profile
sudo ufw allow ApplicationAllow an application by profile
sudo ufw deny ApplicationDeny an application by profile
sudo ufw reloadReload UFW to apply changes
sudo ufw route allow proto tcp from any to any port portAllow routing for a specific port over TCP
sudo ufw route deny proto udp from any to any port portDeny routing for a specific port over UDP

SELinux Cheatsheet

CommandDescription
sestatusCheck the status of SELinux
getenforceGet the current mode of SELinux
setenforce 0Set SELinux to permissive mode
setenforce 1Set SELinux to enforcing mode
semanage boolean -lList all SELinux booleans
semanage boolean -m --on boolean_nameEnable an SELinux boolean
semanage boolean -m --off boolean_nameDisable an SELinux boolean
semanage fcontext -lList all file context mappings
semanage fcontext -a -t type '/path(/.*)?'Add a file context mapping
restorecon -Rv /pathApply file context to files
chcon -t type /pathChange the file context
ls -ZList files with SELinux context
ps -ZList processes with SELinux context
grep AVC /var/log/audit/audit.logSearch for SELinux denials in the audit log
ausearch -m avc -ts recentSearch for recent SELinux denials
audit2allow -w -aDisplay audit log entries that require policy changes
audit2allow -a -M mymoduleGenerate a policy module to allow denials
semodule -i mymodule.ppInstall a policy module
semanage port -lList all SELinux port mappings
semanage port -a -t type -p tcp portAdd a port mapping
semanage port -d -p tcp portDelete a port mapping
semanage permissive -a typeSet a domain to permissive mode
semanage permissive -d typeRemove a domain from permissive mode
seinfoDisplay SELinux policy information
semodule -lList all installed policy modules
semodule -r module_nameRemove an installed policy module
sealert -a /var/log/audit/audit.logAnalyze audit log for SELinux denials

AppArmor Cheatsheet

CommandDescription
aa-statusCheck the status of AppArmor
aa-enforce /etc/apparmor.d/profileSet a profile to enforce mode
aa-complain /etc/apparmor.d/profileSet a profile to complain mode
aa-logprofUpdate profiles based on log events
aa-genprof /path/to/executableGenerate a new profile for an executable
aa-disable /etc/apparmor.d/profileDisable a profile
aa-parse -r /etc/apparmor.d/profileReload a profile
apparmor_parser -r /etc/apparmor.d/profileReload a profile
apparmor_parser -R /etc/apparmor.d/profileRemove a profile from the kernel
aa-unconfinedList unconfined processes
aa-notifyDisplay AppArmor notifications
aa-exec -p profile -- commandExecute a command under a specific profile
aa-audit /etc/apparmor.d/profileSet a profile to audit mode
cat /var/log/syslog \| grep apparmorSearch for AppArmor messages in the syslog
grep "audit" /var/log/kern.logSearch for AppArmor audit messages in the kernel log
ls -lZ /pathList files with AppArmor context
aa-cleanprofRemove unnecessary rules from a profile
aa-enforce /etc/apparmor.d/*Set all profiles to enforce mode
aa-complain /etc/apparmor.d/*Set all profiles to complain mode
journalctl -xe \| grep apparmorSearch for AppArmor events in the journal log
sudo apparmor_parser -r /etc/apparmor.d/usr.bin.programReload a specific AppArmor profile
sudo aa-genprof /path/to/programGenerate a new profile for a program
sudo aa-logprof /var/log/syslogUpdate profiles based on log events
sudo aa-enforce /etc/apparmor.d/usr.bin.programEnforce a specific AppArmor profile
sudo aa-complain /etc/apparmor.d/usr.bin.programSet a specific AppArmor profile to complain mode

LDAP Cheatsheet

CommandDescription
ldapsearch -x -b "base_dn" "(filter)"Search for entries in the LDAP directory
ldapadd -x -D "bind_dn" -W -f file.ldifAdd entries to the LDAP directory
ldapdelete -x -D "bind_dn" -W "dn"Delete entries from the LDAP directory
ldapmodify -x -D "bind_dn" -W -f file.ldifModify entries in the LDAP directory
ldapcompare -x -D "bind_dn" -W "dn" attribute:valueCompare attribute values
ldapwhoami -x -D "bind_dn" -WShow the distinguished name of the authenticated user
ldapmodrdn -x -D "bind_dn" -W "dn" "new_rdn"Modify the RDN of an entry
slapcat -v -l backup.ldifExport the LDAP directory to an LDIF file
slapadd -v -l backup.ldifImport an LDIF file into the LDAP directory
slapindexRebuild the LDAP directory indexes
slapd -d 1Start the LDAP server in debug mode
ldapsearch -LLL -x -b "base_dn" "(filter)" attributeSearch and display specific attributes
ldapsearch -H ldap://ldap.example.com -x -b "base_dn" "(filter)"Search using a specific LDAP URI
ldapsearch -ZZ -x -b "base_dn" "(filter)"Search with StartTLS
ldapadd -ZZ -x -D "bind_dn" -W -f file.ldifAdd entries with StartTLS
ldapmodify -ZZ -x -D "bind_dn" -W -f file.ldifModify entries with StartTLS
ldapdelete -ZZ -x -D "bind_dn" -W "dn"Delete entries with StartTLS
ldapwhoami -ZZ -x -D "bind_dn" -WShow the distinguished name with StartTLS
ldapcompare -ZZ -x -D "bind_dn" -W "dn" attribute:valueCompare attribute values with StartTLS
ldapmodrdn -ZZ -x -D "bind_dn" -W "dn" "new_rdn"Modify the RDN with StartTLS
ldapsearch -Y EXTERNAL -H ldapi:/// -b "cn=config"Search the configuration directory
ldapadd -Y EXTERNAL -H ldapi:/// -f config.ldifAdd configuration entries
ldapmodify -Y EXTERNAL -H ldapi:/// -f config.ldifModify configuration entries
ldapdelete -Y EXTERNAL -H ldapi:/// "dn"Delete configuration entries

LVM Cheatsheet

CommandDescription
pvcreate /dev/sdXCreate a physical volume
pvdisplayDisplay information about physical volumes
pvscanScan all disks for physical volumes
vgcreate vgname /dev/sdXCreate a volume group
vgdisplayDisplay information about volume groups
vgscanScan all disks for volume groups
vgextend vgname /dev/sdXAdd a physical volume to a volume group
vgreduce vgname /dev/sdXRemove a physical volume from a volume group
lvcreate -L size -n lvname vgnameCreate a logical volume
lvcreate -l 100%FREE -n lvname vgnameCreate a logical volume using all free space
lvdisplayDisplay information about logical volumes
lvextend -L+size /dev/vgname/lvnameExtend a logical volume by size
lvextend -l +100%FREE /dev/vgname/lvnameExtend a logical volume using all free space
lvreduce -L-size /dev/vgname/lvnameReduce the size of a logical volume
lvremove /dev/vgname/lvnameRemove a logical volume
lvresize -L size /dev/vgname/lvnameResize a logical volume
lvrename /dev/vgname/oldname newnameRename a logical volume
vgremove vgnameRemove a volume group
pvremove /dev/sdXRemove a physical volume
vgchange -a y vgnameActivate a volume group
vgchange -a n vgnameDeactivate a volume group
vgmerge vgname1 vgname2Merge two volume groups
vgsplit vgname new_vgname /dev/sdXSplit a volume group into two
pvmove /dev/sdXMove physical extents from one physical volume to another
vgcfgbackupBackup volume group metadata
vgcfgrestore vgnameRestore volume group metadata
lvconvert --type raid1 --mirrors 1 /dev/vgname/lvnameConvert a logical volume to RAID1
lvchange -a y /dev/vgname/lvnameActivate a logical volume
lvchange -a n /dev/vgname/lvnameDeactivate a logical volume
lvscanScan for all logical volumes
vgextend vgname /dev/sdXAdd a physical volume to a volume group

ZFS Cheatsheet

CommandDescription
zpool create pool /dev/sdXCreate a new storage pool
zpool destroy poolDestroy a storage pool
zpool statusShow the status of all pools
zpool listList all pools
zpool add pool /dev/sdXAdd a device to a pool
zpool remove pool /dev/sdXRemove a device from a pool
zpool replace pool /dev/sdX /dev/sdYReplace a device in a pool
zpool scrub poolScrub the data in a pool
zpool export poolExport a pool
zpool import poolImport a pool
zfs create pool/datasetCreate a new dataset
zfs destroy pool/datasetDestroy a dataset
zfs listList all datasets
zfs mount pool/datasetMount a dataset
zfs unmount pool/datasetUnmount a dataset
zfs snapshot pool/dataset@snapshotCreate a snapshot of a dataset
zfs rollback pool/dataset@snapshotRoll back to a snapshot
zfs send pool/dataset@snapshotSend a snapshot
zfs receive pool/datasetReceive a snapshot
zfs get property pool/datasetGet a property value
zfs set property=value pool/datasetSet a property value
zfs rename pool/dataset new_nameRename a dataset
zfs clone pool/dataset@snapshot new_datasetClone a snapshot
zfs promote pool/datasetPromote a clone to a full dataset
zfs diff pool/dataset@snapshot1 pool/dataset@snapshot2Show differences between snapshots
zfs upgrade -aUpgrade all ZFS filesystems
zpool upgrade -aUpgrade all ZFS pools
zpool history poolShow command history for a pool
zpool iostat poolShow I/O statistics for a pool
zpool clear poolClear errors in a pool
zpool trim poolTrim free space in a pool
zfs hold tag pool/dataset@snapshotHold a snapshot
zfs release tag pool/dataset@snapshotRelease a held snapshot
zfs inherit property pool/datasetInherit a property from the parent

Btrfs Cheatsheet

CommandDescription
mkfs.btrfs /dev/sdXCreate a Btrfs filesystem
btrfs filesystem showShow Btrfs filesystems
btrfs filesystem df /mountpointShow disk usage of a Btrfs filesystem
btrfs filesystem balance /mountpointBalance a Btrfs filesystem
btrfs filesystem resize size /mountpointResize a Btrfs filesystem
btrfs device add /dev/sdX /mountpointAdd a device to a Btrfs filesystem
btrfs device delete /dev/sdX /mountpointRemove a device from a Btrfs filesystem
btrfs scrub start /mountpointScrub a Btrfs filesystem
btrfs scrub status /mountpointShow scrub status
btrfs balance start /mountpointStart a balance operation
btrfs balance status /mountpointShow balance status
btrfs subvolume create /mountpoint/subvolumeCreate a subvolume
btrfs subvolume delete /mountpoint/subvolumeDelete a subvolume
btrfs subvolume list /mountpointList all subvolumes
btrfs subvolume snapshot /mountpoint/subvolume /mountpoint/snapshotCreate a snapshot
btrfs send /mountpoint/subvolumebtrfs receive /mountpoint/snapshot`
btrfs subvolume set-default subvolid /mountpointSet the default subvolume
btrfs property set /mountpoint/subvolume ro trueSet a subvolume to read-only
btrfs property list /mountpoint/subvolumeList properties of a subvolume
btrfs quota enable /mountpointEnable quotas on a Btrfs filesystem
btrfs qgroup show /mountpointShow quota groups
btrfs qgroup limit size /mountpointSet a quota limit
btrfs rescue zero-log /dev/sdXRepair a corrupted log
btrfs rescue chunk-recover /dev/sdXRecover corrupted chunks
btrfs check /dev/sdXCheck a Btrfs filesystem
btrfs device scanScan for Btrfs devices
btrfs device stats /mountpointShow device statistics
btrfs filesystem defragment /mountpointDefragment a Btrfs filesystem
btrfs quota rescan -w /mountpointRescan quotas
btrfs filesystem sync /mountpointSync a Btrfs filesystem
btrfs replace start /dev/sdX /dev/sdY /mountpointReplace a device in a Btrfs filesystem
btrfs replace status /mountpointShow replace status

Network Troubleshooting Cheatsheet

CommandDescription
ping hostCheck connectivity to a host
ping -c count hostSend a specific number of ping requests
ping -i interval hostSet the interval between ping requests
ping -t ttl hostSet the time-to-live for ping packets
traceroute hostTrace the route to a host
traceroute -m max_ttl hostSet the maximum TTL
traceroute -p port hostSet the destination port
traceroute -I hostUse ICMP echo instead of UDP
traceroute -T hostUse TCP SYN instead of UDP
mtr hostNetwork diagnostic tool combining ping and traceroute
mtr -r hostRun MTR in report mode
mtr -c count hostSet the number of pings in MTR
netstat -tulnList all listening ports and services
netstat -iShow network interfaces
netstat -rnShow the routing table
netstat -sDisplay network statistics
netstat -plntShow listening TCP ports
ss -tulnList all listening ports and services (ss command)
ss -iShow network interfaces (ss command)
ss -rnShow the routing table (ss command)
ss -sDisplay network statistics (ss command)
ss -plntShow listening TCP ports (ss command)
ip addr showDisplay all IP addresses
ip link showShow network interfaces
ip route showDisplay the routing table
ip link set dev iface upBring an interface up
ip link set dev iface downBring an interface down
ifconfigDisplay network interfaces
ifconfig iface upBring an interface up
ifconfig iface downBring an interface down
ifconfig iface inet addrAssign an IP address to an interface
ifconfig iface hw ether MACAssign a MAC address to an interface
ethtool ifaceDisplay Ethernet device settings
ethtool -s iface speed 1000 duplex full autoneg onSet Ethernet device speed and duplex
tcpdump -i ifaceCapture packets on an interface
tcpdump -n host hostCapture packets to/from a specific host
tcpdump -nn port portCapture packets on a specific port
tcpdump -w file.pcapWrite packets to a file
tcpdump -r file.pcapRead packets from a file
dig domainDNS lookup for a domain
dig +short domainShort DNS lookup for a domain
dig -x ipReverse DNS lookup
nslookup domainDNS lookup for a domain (nslookup)
nslookupEnter interactive mode (nslookup)
nslookup domain serverDNS lookup using a specific DNS server

System Diagnostics and Logging Cheatsheet

dmesg

CommandDescription
dmesgDisplay all messages from the kernel ring buffer
`dmesgless`
`dmesggrep pattern`
dmesg -cClear the ring buffer after printing
dmesg -TDisplay human-readable timestamps for each message
dmesg -HEnable colorized and human-readable output
dmesg -l levelFilter messages by log level (e.g., emerg, alert, crit, err, warn, notice, info, debug)
dmesg -n levelSet the log level of messages to print
dmesg -f facilityFilter messages by facility (e.g., kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, authpriv, ftp, local0-local7)
dmesg -rRaw output, no human-readable timestamps
dmesg --clearClear the kernel ring buffer
dmesg --level levelSet the log level for printing messages
dmesg --facility facilitySet the facility for printing messages
dmesg -wKeep waiting for new messages and print them as they come
dmesg --followAlias for -w, keep waiting for new messages

journalctl

CommandDescription
journalctlView the systemd journal
journalctl -bShow messages from the current boot
journalctl -kShow only kernel messages
journalctl -u serviceShow messages for a specific service
journalctl -fFollow new messages as they appear (similar to tail -f)
journalctl -rShow messages in reverse chronological order
journalctl --since "time"Show messages since a specific time
journalctl --until "time"Show messages until a specific time
journalctl -p levelShow messages of a specific priority level (e.g., emerg, alert, crit, err, warn, notice, info, debug)
journalctl -xeShow the last few log entries with details about system errors
journalctl --disk-usageShow the disk space used by the journal
journalctl --vacuum-time=timeRemove journal files older than the specified time
journalctl --vacuum-size=sizeRemove old journal files until the total size is below the specified size
journalctl -o json-prettyOutput logs in pretty JSON format

rsyslog (or syslog in general)

Command/ConfigurationDescription
/etc/rsyslog.confMain configuration file for rsyslog
/etc/rsyslog.d/Directory for additional configuration files
sudo systemctl restart rsyslogRestart the rsyslog service
logger "message"Add a message to the system log
/var/log/messagesGeneral system log
/var/log/secureAuthentication and security related messages
/var/log/maillogMail server logs
/var/log/cronCron job logs
/var/log/boot.logSystem boot log
/var/log/dmesgKernel ring buffer log

top / htop

CommandDescription
topDisplay real-time system information including tasks and load
htopInteractive process viewer (requires installation)
top -u usernameShow only processes for a specific user
top -p PIDShow only the specified PID(s)
htop -u usernameShow only processes for a specific user (in htop)

free

CommandDescription
freeDisplay memory usage
free -hDisplay memory usage in human-readable format
free -mDisplay memory usage in megabytes
free -gDisplay memory usage in gigabytes

vmstat

CommandDescription
vmstatDisplay virtual memory statistics
vmstat 1Display virtual memory statistics every second
vmstat -sDisplay memory statistics
vmstat -dDisplay disk statistics
vmstat -tDisplay timestamps with the output

iostat

CommandDescription
iostatDisplay CPU and I/O statistics
iostat -xDisplay extended statistics
iostat -dDisplay device utilization statistics
iostat -cDisplay only CPU statistics
iostat -p ALLDisplay statistics for all devices and partitions

mpstat

CommandDescription
mpstatDisplay CPU usage
mpstat -P ALLDisplay CPU usage for all processors
mpstat 1 5Display CPU usage every second for 5 times

sar

CommandDescription
sarCollect and report system activity
sar -u 1 3Report CPU utilization every second for 3 times
sar -rReport memory utilization
sar -n DEVReport network statistics
sar -bReport I/O and transfer rate statistics

netstat / ss

CommandDescription
netstat -tulnList all listening ports
netstat -iDisplay network interfaces
netstat -rnDisplay routing table
netstat -sDisplay network statistics
ss -tulnList all listening ports (ss command)
ss -iDisplay network interfaces (ss command)
ss -rnDisplay routing table (ss command)
ss -sDisplay network statistics (ss command)

iftop (requires installation)

CommandDescription
iftopDisplay real-time network bandwidth usage
iftop -i interfaceDisplay network bandwidth usage for a specific interface
iftop -PShow ports
iftop -nShow numerical addresses rather than resolving hosts

tcpdump

CommandDescription
tcpdump -i interfaceCapture packets on a specific interface
tcpdump -n host hostCapture packets to/from a specific host
tcpdump -nn port portCapture packets on a specific port
tcpdump -w file.pcapWrite captured packets to a file
tcpdump -r file.pcapRead packets from a file

Important /proc Subdirectories and Files

Directory/FileDescription
/proc/cpuinfoDetailed information about the CPU, such as model, cores, and speed
/proc/meminfoDetailed information about memory usage
/proc/versionKernel version and build information
/proc/cmdlineKernel command line used to boot the system
/proc/devicesLists all character and block devices currently configured
/proc/diskstatsDisk I/O statistics
/proc/uptimeSystem uptime information
/proc/loadavgLoad average of the system
/proc/mountsMounted filesystems
/proc/partitionsInformation about disk partitions
/proc/swapsSwap space utilization
/proc/sysKernel tunable parameters (sysctl)
/proc/sys/kernelKernel-related parameters
/proc/sys/netNetwork-related parameters
/proc/netNetwork status information
/proc/interruptsNumber of interrupts per CPU per I/O device
/proc/iomemMemory map for the system
/proc/ioportsI/O port usage
/proc/modulesLoaded kernel modules
/proc/kallsymsKernel symbol table
/proc/kcorePseudo-file representing the physical memory of the system
/proc/slabinfoKernel slab allocator information
/proc/selfProcess-specific information for the current process
/proc/self/cmdlineCommand line of the current process
/proc/self/environEnvironment variables of the current process
/proc/self/exeSymlink to the executable of the current process
/proc/self/statusCurrent process status information
/proc/self/limitsResource limits of the current process
/proc/self/mountsMounts of the current process
/proc/self/cgroupCgroup membership of the current process
/proc/self/fdFile descriptors opened by the current process
/proc/self/fdinfoDetailed information about file descriptors
/proc/self/mapsMemory maps of the current process
/proc/self/smapsExtended memory maps of the current process
/proc/self/memMemory of the current process
/proc/self/taskTasks (threads) of the current process
/proc/[pid]/Information specific to process with PID
/proc/[pid]/cmdlineCommand line of the process with PID
/proc/[pid]/environEnvironment variables of the process with PID
/proc/[pid]/exeSymlink to the executable of the process with PID
/proc/[pid]/statusStatus information of the process with PID
/proc/[pid]/limitsResource limits of the process with PID
/proc/[pid]/mountsMounts of the process with PID
/proc/[pid]/cgroupCgroup membership of the process with PID
/proc/[pid]/fdFile descriptors opened by the process with PID
/proc/[pid]/fdinfoDetailed information about file descriptors of the process with PID
/proc/[pid]/mapsMemory maps of the process with PID
/proc/[pid]/smapsExtended memory maps of the process with PID
/proc/[pid]/memMemory of the process with PID
/proc/[pid]/taskTasks (threads) of the process with PID

MPV Hotkeys Cheatsheet

HotkeyDescription
SpaceToggle play/pause
fToggle fullscreen
mMute/unmute audio
9 / (Decrease volume
0 / )Increase volume
[Decrease playback speed
]Increase playback speed
{Halve playback speed
}Double playback speed
backspaceReset playback speed to normal
Left ArrowSeek backward 5 seconds
Right ArrowSeek forward 5 seconds
Up ArrowSeek forward 60 seconds
Down ArrowSeek backward 60 seconds
Shift+Left ArrowSeek backward 1 second
Shift+Right ArrowSeek forward 1 second
Ctrl+Left ArrowSeek backward 10 minutes
Ctrl+Right ArrowSeek forward 10 minutes
.Move forward one frame (pause required)
,Move backward one frame (pause required)
oShow file info
IShow codec info
qQuit
QForce quit (without saving the resume position)
sTake a screenshot
STake a screenshot without subtitles
Ctrl+sTake a screenshot and include the OSD
TToggle displaying time
Ctrl+oCycle through OSD (On-Screen Display) levels
vToggle subtitles
jCycle through subtitles
JCycle through secondary subtitles
#Toggle subtitle visibility
zAdjust subtitle delay backward
xAdjust subtitle delay forward
rRotate video
pToggle between current and previous subtitle track
lAdjust audio delay backward
kAdjust audio delay forward
Ctrl++Increase subtitle font size
Ctrl+-Decrease subtitle font size
Alt++Increase subtitle border size
Alt+-Decrease subtitle border size
Ctrl+rToggle random playback
Ctrl+shift+rToggle looping playback
Ctrl+pToggle playlist navigation display
Ctrl+uReload playlist
Ctrl+EnterToggle between fullscreen and windowed mode
EscExit fullscreen or close OSD menu
hSeek to the previous chapter
lSeek to the next chapter
yAdjust subtitle delay back by 0.1 seconds
YAdjust subtitle delay forward by 0.1 seconds
tToggle stay-on-top mode
Ctrl+fToggle autofit
Ctrl+cCopy current file path to clipboard
Ctrl+vPaste URL/file path from clipboard and open

Linux Journey

For this I will only be taking note of material I would like to reaffirm or commit to memory. Therefore these notes are not exhaustive or that verbose since much of the material on this site I already know Link

Grasshopper

Text Fu

Data Streams (STDIO)

  • Standard In (stdin)
    • Numerically represented as 0
  • Standard Out (stdout)
    • Numerically represented as 1
  • Standard Error (stderr)
    • Numerically represented as 2

User Management

  • /etc/passwd
    • Contains username, default shell, home directory, UID and GID
  • /etc/shadow
    • Contains encrypted password, change history, constraints
  • /etc/group
    • Contains groups and users

Permissions

  • File type followed by three field of three bits define permissions
  • d | rwx | rwx | rwx
  • So it is octal, decimal representation is 0-7 or null
  • umask masks off to define default set of permissions on new files
  • The set user id or SUID bit enables executing a file as the owner of the file. x is replaced with s. It is numerically represented as 4 prepended.
  • The set group id or GUID bit is a synonymous concept, numerically represented as 2 prepended S represents a SUID or GUID bit that it set, while the executable bit itself is not
  • The sticky bit allows only the owner or root to edit a file. Numerically represented as 1 prepended. Represented as t appended. T represents a sticky bit where the executable bit itself is not set

Process Permissions:

  • Process UIDs
    • effective user id: permission of running user
    • real user id: user that launched process
    • saved user id: essentially a cached id that allows for switching between root uid is 0

    When running the passwd command, your effective UID is your user ID, let's say its 500 for now. Oh but wait, remember the passwd command has the SUID permission enabled. So when you run it, your effective UID is now 0 (0 is the UID of root). Now this program can access files as root. Let's say you get a little taste of power and you want to modify Sally's password, Sally has a UID of 600. Well you'll be out of luck, fortunately the process also has your real UID in this case 500. It knows that your UID is 500 and therefore you can't modify the password of UID of 600. (This of course is always bypassed if you are a superuser on a machine and can control and change everything). Since you ran passwd, it will start the process off using your real UID, and it will save the UID of the owner of the file (effective UID), so you can switch between the two. No need to modify all files with root access if it's not required. Most of the time the real UID and the effective UID are the same, but in such cases as the passwd command they will change.

Processes

  • Controlling terminal: the terminal a process is bound to
  • Processes are instances of a program
  • ps aux

When a new process is created, an existing process basically clones itself using something called the fork system call (system calls will be discussed very far into the future). The fork system call creates a mostly identical child process, this child process takes on a new process ID (PID) and the original process becomes its parent process and has something called a parent process ID PPID. Afterwards, the child process can either continue to use the same program its parent was using before or more often use the execve system call to launch up a new program. This system call destroys the memory management that the kernel put into place for that process and sets up new ones for the new program.

  • Orphans: Processes that have no parent and are adopted and queued for killing by init
  • Zombies: Children that die before wait() is called. They will be reaped if parent calls wait() or is adopted then killed by init

Signals

  • Software interrupts that can for killing, suspending, or communicating
  • Processes have signal masks

Common signals Each signal is defined by integers with symbolic names that are in the form of SIGxxx. Some of the most common signals are: SIGHUP or HUP or 1: Hangup SIGINT or INT or 2: Interrupt SIGKILL or KILL or 9: Kill SIGSEGV or SEGV or 11: Segmentation fault SIGTERM or TERM or 15: Software termination SIGSTOP or STOP: Stop Numbers can vary with signals so they are usually referred by their names.

  • kill sends terminate sig by default or signal of choosing through option -sig_num

Niceness

  • Process CPU priority
    • Number -20 through 19
    • Higher == Lower Priority
    • Lower == Higher Priority

/proc

  • /proc contains info on pids abstracted as files in /proc/"pid_num"

Job Control

  • & runs job in background of controlling terminal
  • jobs outputs background jobs
  • CTRL-Z sends current jobs to background
  • fg moves background jobs to foreground
  • kill can kill background jobs as well

Packaging

  • tar xvf is good for archiving
  • This site discusses gunzip for compressing.
  • tar supports compressing with it: tar czvf, and uncompressing: tar xzfv

Journeyman

Devices

  • /dev is where device files reside including pseudo devices

Remember in the ls command you can see the type of file with the first bit on each line. Device files are denoted as the following: c - character b - block p - pipe s - socket

  • Character: sends data one char at a time
  • Block: large fized sized blocks (storage)
  • Pipe: pipes data form one process to another
  • Socket: Similar to pipe but with multiple processes simultaneously

Naming

  • SCSI protocol: prefixed sd the a-z
  • zero null and random
  • PATA for older hardware prefixed with hd

sysfs

  • /sys contains information on devices

udev

The udev system dynamically creates and removes device files for us depending on whether or not they are connected.

  • udevd is the associated daemon
  • rules located in /etc/udev/rules.d

Listing and dd

  • lsusb, lspci, and lsscsi
  • dd for writing data THE DISK DESTROYER

The Filesystem

The majority of this section is already learned

Inodes

  • Index table of references to file metadata and the data blocks themselves
  • Created at filesystem creation
  • Can be exhausted

In a typical filesystem (not all work the same), each inode contains 15 pointers, the first 12 pointers point directly to the data blocks. The 13th pointer, points to a block containing pointers to more blocks, the 14th pointer points to another nested block of pointers, and the 15th pointer points yet again to another block of pointers!

Boot The System

initrd - Specifies the location of initial RAM disk (we'll talk more about this in the next lesson). BOOT_IMAGE - This is where the kernel image is located root - The location of the root filesystem, the kernel searches inside this location to find init. It is often represented by it's UUID or the device name such as /dev/sda1. ro - This parameter is pretty standard, it mounts the fileystem as read-only mode. quiet - This is added so that you don't see display messages that are going on in the background during boot. splash - This lets the splash screen be shown.

Kernel

  • initrd and initramfs are temp file systems that exists to load necessary drivers for hardware communication during boot

Kernel

  • Hardware --> Kernel --> Userspace
  • x86 privledge levels or protection rings: 3-->0

System Calls

  • C code that provide user space processes means of communicating kernel
  • Uses API
  • Programs contain syscall wrappers for traps
  • trap gets caught and references syscall table
  • strace outputs syscalls of process

Kernel Location

You will see multiple files for different kernel versions: vmlinuz - this is the actual linux kernel initrd - as we've discussed before, the initrd is used as a temporary file system, used before loading the kernel System.map - symbolic lookup table config - kernel configuration settings, if you are compiling your own kernel, you can set which modules can be loadess

Kernel Modules

  • lsmod, modprobe, and /etc/modprobe.d/ Drivers can be a kind of kernel module if not built in

Init

SysV

0: Shutdown 1: Single User Mode 2: Multiuser mode without networking 3: Multiuser mode with networking 4: Unused 5: Multiuser mode with networking and GUI 6: Reboot

SystemD

  • Target and dependency based >First, systemd loads its configuration files, usually located in /etc/systemd/system or /usr/lib/systemd/system Then it determines its boot goal, which is usually default.target Systemd figures out the dependencies of the boot target and activates them

poweroff.target - shutdown system rescue.target - single user mode multi-user.target - multiuser with networking graphical.target - multiuser with networking and GUI reboot.target - restart

  • Units are files that contain config directives

The most common units are: Service units - these are the services we've been starting and stopping, these unit files end in .service Mount units - These mount filesystems, these unit files end in .mount Target units - These group together other units, the files end in .target

Process Utilization

  • top
  • lsof
  • fuser
  • view threads with: ps m
  • uptime, iostat, /proc/cpuinfo, vmstat, sar
  • Cron jobs: crontab -e

Logging

  • syslog is a service that sends info the the logger
  • daemon is syslogd or rsyslogd
  • logs are generally in /var
  • `/var/log/syslog
  • `var/log/kern.log
  • `/var/log/auth.log
  • logrotate to rotate logs, /etc/logrotate.d

I want to pivot off of this reading by taking notes from the Red Hat Wiki specifically on SystemD. All in all this website is a great resource and I highly recommend it for anyone getting into Linux.

Math

Notes from math classes I've taken transcribed to Mathjax for mdbook.

Single Variable Calculus

Limits and Continuity

Definition of a Limit: \[ \lim_{x \to c} f(x) = L \]

One-Sided Limits: \[ \lim_{x \to c^+} f(x) = L \] \[ \lim_{x \to c^-} f(x) = L \]

Limit Laws: \[ \lim_{x \to c} [f(x) + g(x)] = \lim_{x \to c} f(x) + \lim_{x \to c} g(x) \] \[ \lim_{x \to c} [f(x) - g(x)] = \lim_{x \to c} f(x) - \lim_{x \to c} g(x) \] \[ \lim_{x \to c} [f(x) \cdot g(x)] = \lim_{x \to c} f(x) \cdot \lim_{x \to c} g(x) \] \[ \lim_{x \to c} \left[ \frac{f(x)}{g(x)} \right] = \frac{\lim_{x \to c} f(x)}{\lim_{x \to c} g(x)} \]

Continuity: A function ( f(x) ) is continuous at ( x = c ) if:

  1. ( f(c) ) is defined.
  2. ( \lim_{x \to c} f(x) ) exists.
  3. ( \lim_{x \to c} f(x) = f(c) ).

Derivatives

Definition of the Derivative: \[ f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} \]

Power Rule: \[ \frac{d}{dx} [x^n] = nx^{n-1} \]

Product Rule: \[ \frac{d}{dx} [uv] = u'v + uv' \]

Quotient Rule: \[ \frac{d}{dx} \left[ \frac{u}{v} \right] = \frac{u'v - uv'}{v^2} \]

Chain Rule: \[ \frac{d}{dx} f(g(x)) = f'(g(x)) g'(x) \]

Higher-Order Derivatives: \[ f''(x) = \frac{d^2 f}{dx^2} \]

Applications of Derivatives

Critical Points: Points where ( f'(x) = 0 ) or ( f'(x) ) does not exist.

Increasing/Decreasing Test:

  • If ( f'(x) > 0 ) on an interval, ( f(x) ) is increasing on that interval.
  • If ( f'(x) < 0 ) on an interval, ( f(x) ) is decreasing on that interval.

First Derivative Test:

  • If ( f' ) changes from positive to negative at ( c ), ( f(c) ) is a local maximum.
  • If ( f' ) changes from negative to positive at ( c ), ( f(c) ) is a local minimum.

Concavity and Inflection Points:

  • ( f''(x) > 0 ) on an interval, ( f ) is concave up on that interval.
  • ( f''(x) < 0 ) on an interval, ( f ) is concave down on that interval.
  • Inflection points occur where ( f''(x) = 0 ) and changes sign.

Second Derivative Test:

  • If ( f''(c) > 0 ), ( f(c) ) is a local minimum.
  • If ( f''(c) < 0 ), ( f(c) ) is a local maximum.

Optimization: Use derivatives to find the maximum and minimum values of a function in a given interval.

Related Rates: Use derivatives to relate the rates of change of two or more related variables.

Integrals

Indefinite Integral (Antiderivative): \[ \int f(x) , dx = F(x) + C \] where ( F'(x) = f(x) ) and ( C ) is the constant of integration.

Basic Integration Rules: \[ \int x^n , dx = \frac{x^{n+1}}{n+1} + C ] \[ \int e^x , dx = e^x + C \] \[ \int \sin x , dx = -\cos x + C \] \[ \int \cos x , dx = \sin x + C \]

Definite Integral: \[ \int_a^b f(x) , dx \] represents the area under the curve ( f(x) ) from ( x = a ) to ( x = b ).

Fundamental Theorem of Calculus:

  1. \[ F(x) = \int_a^x f(t) , dt \implies F'(x) = f(x) \]
  2. \[ \int_a^b f(x) , dx = F(b) - F(a) \] where ( F ) is an antiderivative of ( f ).

Integration by Substitution: \[ \int f(g(x))g'(x) , dx = \int f(u) , du \] where ( u = g(x) ).

Integration by Parts: \[ \int u , dv = uv - \int v , du \]

Applications of Integrals

Area Between Curves: \[ \int_a^b [f(x) - g(x)] , dx \] where ( f(x) ) is the upper function and ( g(x) ) is the lower function.

Volume of Solids of Revolution (Disk Method): \[ V = \pi \int_a^b [f(x)]^2 , dx \]

Volume of Solids of Revolution (Washer Method): \[ V = \pi \int_a^b \left[ [R(x)]^2 - [r(x)]^2 \right] , dx \]

Arc Length: \[ L = \int_a^b \sqrt{1 + [f'(x)]^2} , dx \]

Surface Area: \[ SA = 2\pi \int_a^b f(x) \sqrt{1 + [f'(x)]^2} , dx \]

Calculus 2 Formulas

Techniques of Integration

Integration by Partial Fractions: For a rational function ( \frac{P(x)}{Q(x)} ), decompose into partial fractions before integrating.

Trigonometric Integrals: \[ \int \sin^m x \cos^n x , dx \] Use reduction formulas or trigonometric identities.

Trigonometric Substitution: Use substitutions like ( x = a \sin \theta ), ( x = a \tan \theta ), or ( x = a \sec \theta ) to simplify integrals.

Improper Integrals: \[ \int_a^\infty f(x) , dx = \lim_{b \to \infty} \int_a^b f(x) , dx \] \[ \int_{-\infty}^\infty f(x) , dx = \lim_{a \to -\infty} \lim_{b \to \infty} \int_a^b f(x) , dx \]

Series

Sequences: A sequence is an ordered list of numbers defined by a formula ( a_n ).

Series: A series is the sum of the terms of a sequence. \[ \sum_{n=1}^\infty a_n \]

Geometric Series: \[ \sum_{n=0}^\infty ar^n = \frac{a}{1-r} \quad \text{for} \quad |r| < 1 \]

Convergence Tests:

  • Integral Test: \[ \sum_{n=1}^\infty a_n \quad \text{and} \quad \int_1^\infty f(x) , dx \quad \text{either both converge or both diverge} \]
  • Comparison Test: If ( 0 \le a_n \le b_n ) and ( \sum b_n ) converges, then ( \sum a_n ) converges.
  • Ratio Test: \[ \lim_{n \to \infty} \left| \frac{a_{n+1}}{a_n} \right| = L ]
    • If ( L < 1 ), the series converges.
    • If ( L > 1 ), the series diverges.
    • If ( L = 1 ), the test is inconclusive.
  • Root Test: \[ \lim_{n \to \infty} \sqrt[n]{|a_n|} = L ]
    • If ( L < 1 ), the series converges.
    • If ( L > 1 ), the series diverges.
    • If ( L = 1 ), the test is inconclusive.

Power Series: \[ \sum_{n=0}^\infty c_n (x - a)^n \] with radius of convergence ( R ).

Taylor Series: \[ f(x) = \sum_{n=0}^\infty \frac{f^n(a)}{n!} (x - a)^n \]

Maclaurin Series: \[ f(x) = \sum_{n=0}^\infty \frac{f^n(0)}{n!} x^n \]

Parametric Equations and Polar Coordinates

Parametric Equations:

  • A curve is defined by ( x = f(t) ) and ( y = g(t) ).

Slope of a Parametric Curve: \[ \frac{dy}{dx} = \frac{\frac{dy}{dt}}{\frac{dx}{dt}} \]

Arc Length of a Parametric Curve: \[ L = \int_a^b \sqrt{\left( \frac{dx}{dt} \right)^2 + \left( \frac{dy}{dt} \right)^2} , dt \]

Polar Coordinates:

  • Points are defined by ( (r, \theta) ).

Converting Polar to Cartesian: \[ x = r \cos \theta \] \[ y = r \sin \theta \]

Converting Cartesian to Polar: \[ r = \sqrt{x^2 + y^2} \] \[ \theta = \tan^{-1} \left( \frac{y}{x} \right) \]

Area in Polar Coordinates: \[ A = \frac{1}{2} \int_{\alpha}^{\beta} r^2 , d\theta \]

Arc Length in Polar Coordinates: \[ L = \int_{\alpha}^{\beta} \sqrt{\left( \frac{dr}{d\theta} \right)^2 + r^2} , d\theta \]

Differential Equations

Separable Differential Equations: \[ \frac{dy}{dx} = g(x)h(y) \] Separate and integrate: \[ \int \frac{1}{h(y)} , dy = \int g(x) , dx \]

Linear First-Order Differential Equations: \[ \frac{dy}{dx} + P(x)y = Q(x) \] Solve using the integrating factor: \[ \mu(x) = e^{\int P(x) , dx} \]

General Solution: \[ y(x) = \frac{1}{\mu(x)} \left( \int \mu(x) Q(x) , dx + C \right) \]

Applications of Differential Equations

Exponential Growth and Decay: \[ \frac{dy}{dt} = ky \] Solution: \[ y(t) = y_0 e^{kt} \]

Newton's Law of Cooling: \[ \frac{dT}{dt} = k(T - T_{\text{env}}) \] Solution: \[ T(t) = T_{\text{env}} + (T_0 - T_{\text{env}}) e^{kt} \]

Logistic Growth: \[ \frac{dP}{dt} = rP \left( 1 - \frac{P}{K} \right) \] Solution: \[ P(t) = \frac{KP_0 e^{rt}}{K + P_0 (e^{rt} - 1)} \]

Calculus 3 Formulas

Vectors

Dot Product: \[ \mathbf{a} \cdot \mathbf{b} = a_1 b_1 + a_2 b_2 + a_3 b_3 \] \[ \mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| |\mathbf{b}| \cos \theta \]

Projection of (\mathbf{a}) onto (\mathbf{b}): \[ \text{proj}_{\mathbf{b}} \mathbf{a} = \frac{\mathbf{a} \cdot \mathbf{b}}{\mathbf{b} \cdot \mathbf{b}} \mathbf{b} \]

Cross Product: \[ \mathbf{a} \times \mathbf{b} = \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\ a_1 & a_2 & a_3 \\ b_1 & b_2 & b_3 \ \end{vmatrix} \] \[ |\mathbf{a} \times \mathbf{b}| = |\mathbf{a}| |\mathbf{b}| \sin \theta \]

Area of Parallelogram (in vectors): \[ \text{Area} = |\mathbf{a} \times \mathbf{b}| \]

Volume of Parallelepiped: \[ \text{Volume} = |\mathbf{a} \cdot (\mathbf{b} \times \mathbf{c})| \]

Equation of a Line: \[ \mathbf{r} = \mathbf{r_0} + t \mathbf{v} \]

Parametric Equation of a Line: \[ \begin{cases} x = x_0 + t a \\ y = y_0 + t b \\ z = z_0 + t c \ \end{cases} \]

Symmetric Equation of a Line: \[ \frac{x - x_0}{a} = \frac{y - y_0}{b} = \frac{z - z_0}{c} \]

Equation of a Plane (standard form): \[ ax + by + cz = d \]

Equation of a Plane (general form): \[ ax + by + cz + d = 0 \]

Distance from Point to Line: \[ D = \frac{|\mathbf{PQ} \times \mathbf{v}|}{|\mathbf{v}|} \]

Distance from Point to Plane: \[ D = \frac{|ax_1 + by_1 + cz_1 + d|}{\sqrt{a^2 + b^2 + c^2}} \]

Distance Between Parallel Planes: \[ D = \frac{|d_1 - d_2|}{\sqrt{a^2 + b^2 + c^2}} \]

Position Vector for a Projectile: \[ \mathbf{r}(t) = \left( v_{0x} t \right) \mathbf{i} + \left( v_{0y} t - \frac{1}{2} g t^2 \right) \mathbf{j} \]

Unit Tangent Vector: \[ \mathbf{T}(t) = \frac{\mathbf{r}'(t)}{|\mathbf{r}'(t)|} \]

Principal Unit Normal Vector: \[ \mathbf{N}(t) = \frac{\mathbf{T}'(t)}{|\mathbf{T}'(t)|} \]

Tangential and Normal Components of Acceleration: \[ a_T = \mathbf{a} \cdot \mathbf{T} \] \[ a_N = \sqrt{|\mathbf{a}|^2 - a_T^2} \]

Arc Length of a Space Curve: \[ s = \int_a^b |\mathbf{r}'(t)| , dt \]

Curvature: \[ \kappa = \frac{|\mathbf{T}'(t)|}{|\mathbf{r}'(t)|} = \frac{|\mathbf{r}'(t) \times \mathbf{r}''(t)|}{|\mathbf{r}'(t)|^3} \]

Angle of Inclination: \[ \theta = \arccos\left(\frac{a}{\sqrt{a^2 + b^2 + c^2}}\right) \]

Tangent Plane to Level Surface: \[ z - z_0 = f_x(x_0, y_0)(x - x_0) + f_y(x_0, y_0)(y - y_0) \]

Normal Line: \[ \frac{x - x_0}{f_x(x_0, y_0)} = \frac{y - y_0}{f_y(x_0, y_0)} = \frac{z - z_0}{-1} \]

Vector Fields: \[ \mathbf{F}(x, y, z) = P(x, y, z) \mathbf{i} + Q(x, y, z) \mathbf{j} + R(x, y, z) \mathbf{k} \]

Inverse Square Fields: \[ \mathbf{F}(\mathbf{r}) = \frac{k \mathbf{r}}{|\mathbf{r}|^3} \]

Conservative Vector Field Tests: \[ \nabla \times \mathbf{F} = \mathbf{0} \]

Curl of a Vector Field: \[ \nabla \times \mathbf{F} = \left( \frac{\partial R}{\partial y} - \frac{\partial Q}{\partial z} \right) \mathbf{i} + \left( \frac{\partial P}{\partial z} - \frac{\partial R}{\partial x} \right) \mathbf{j} + \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) \]

Divergence of a Vector Field: \[ \nabla \cdot \mathbf{F} = \frac{\partial P}{\partial x} + \frac{\partial Q}{\partial y} + \frac{\partial R}{\partial z} \]

Line Integrals: \[ \int_C f(x, y, z) , ds \]

Line Integrals of a Vector Field: \[ \int_C \mathbf{F} \cdot d\mathbf{r} \]

Differential Form of Line Integral: \[ \int_C P , dx + Q , dy + R , dz \]

Fundamental Theorem of Line Integrals: \[ \int_C \nabla f \cdot d\mathbf{r} = f(\mathbf{r}(b)) - f(\mathbf{r}(a)) \]

Independence of Path: \[ \int_C \mathbf{F} \cdot d\mathbf{r} = 0 \ \text{if} \ \mathbf{F} \ \text{is conservative} \]

Partial Derivatives

Total Differential: \[ dz = f_x , dx + f_y , dy \]

Chain Rule for Functions of One Independent Variable: \[ \frac{dz}{dt} = \frac{\partial z}{\partial x} \frac{dx}{dt} + \frac{\partial z}{\partial y} \frac{dy}{dt} \]

Chain Rule for Functions of Two Independent Variables: \[ \frac{\partial z}{\partial t} = \frac{\partial z}{\partial x} \frac{\partial x}{\partial t} + \frac{\partial z}{\partial y} \frac{\partial y}{\partial t} \]

Implicit Partial Differentiation: \[ \frac{\partial z}{\partial x} = -\frac{F_x}{F_z} \] \[ \frac{\partial z}{\partial y} = -\frac{F_y}{F_z} \]

Directional Derivative: \[ D_{\mathbf{u}} f = \nabla f \cdot \mathbf{u} \]

The Gradient of a Function: \[ \nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right) \]

Second Partials Test: \[ D = f_{xx} f_{yy} - (f_{xy})^2 \]

Extreme Value Theorem: \[ f \ \text{has a local maximum/minimum at} \ (a, b) \ \text{if} \ D > 0 \ \text{and} \ f_{xx} > 0 \ (\text{minimum}) \ \text{or} \ f_{xx} < 0 \ (\text{maximum}) \]

Lagrange Multipliers: \[ \nabla f = \lambda \nabla g \]

Iterated, Double, and Repeated Integrals

Rectangular Regions: \[ \int_a^b \int_c^d f(x, y) , dy , dx \]

Fubini's Theorem: \[ \int_a^b \int_c^d f(x, y) , dy , dx = \int_c^d \int_a^b f(x, y) , dx , dy \]

General Regions: \[ \int_{\text{Region}} f(x, y) , dA \]

Average Value of a Function Over a Region: \[ \frac{1}{\text{Area}} \int_{\text{Region}} f(x, y) , dA \]

Double Integrals in Polar Coordinates: \[ \int_a^b \int_{r_1(\theta)}^{r_2(\theta)} f(r, \theta) , r , dr , d\theta \]

Triple Integrals in Cylindrical Coordinates: \[ \int_a^b \int_{r_1(\theta)}^{r_2(\theta)} \int_{z_1(r, \theta)}^{z_2(r, \theta)} f(r, \theta, z) , r , dz , dr , d\theta \]

Triple Integrals in Spherical Coordinates: \[ \int_a^b \int_{0}^{\pi} \int_{0}^{2\pi} f(\rho, \phi, \theta) , \rho^2 \sin(\phi) , d\theta , d\phi , d\rho \]

Surface Area: \[ \iint_S |\mathbf{r}_u \times \mathbf{r}_v| , dA \]

Change of Variables for Double Integrals: \[ \iint_R f(x, y) , dx , dy = \iint_{R'} f(g(u, v), h(u, v)) \left| \frac{\partial(x, y)}{\partial(u, v)} \right| , du , dv \]

Triple Integrals: \[ \iiint_V f(x, y, z) , dV \]

Green's Theorem: \[ \oint_C (P , dx + Q , dy) = \iint_R \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) dA \]

Alternate Forms of Green's Theorem: \[ \oint_C (L , dx + M , dy + N , dz) = \iint_R (\nabla \times \mathbf{F}) \cdot \mathbf{n} , dA \]

Parametric Surfaces: \[ \mathbf{r}(u, v) = \langle x(u, v), y(u, v), z(u, v) \rangle \]

Area of Parametric Surface: \[ \iint_D |\mathbf{r}_u \times \mathbf{r}_v| , du , dv \]

Surface Integrals: \[ \iint_S f(x, y, z) , dS \]

Flux Integrals: \[ \iint_S \mathbf{F} \cdot \mathbf{n} , dS \]

Divergence Theorem: \[ \iiint_V (\nabla \cdot \mathbf{F}) , dV = \iint_S \mathbf{F} \cdot \mathbf{n} , dS \]

Stokes' Theorem: \[ \iint_S (\nabla \times \mathbf{F}) \cdot \mathbf{n} , dS = \oint_C \mathbf{F} \cdot d\mathbf{r} \]

Surfaces

Ellipsoid: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 \]

Hyperboloid of One Sheet: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} - \frac{z^2}{c^2} = 1 \]

Hyperboloid of Two Sheets: \[ \frac{x^2}{a^2} - \frac{y^2}{b^2} - \frac{z^2}{c^2} = 1 \]

Elliptic Cone: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} - \frac{z^2}{c^2} = 0 \]

Elliptic Paraboloid: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} = z \]

Hyperbolic Paraboloid (saddle): \[ \frac{x^2}{a^2} - \frac{y^2}{b^2} = z \]

Coordinate System Conversions

Cylindrical to Rectangular: \[ x = r \cos \theta \] \[ y = r \sin \theta \] \[ z = z \]

Spherical to Rectangular: \[ x = \rho \sin \phi \cos \theta \] \[ y = \rho \sin \phi \sin \theta \] \[ z = \rho \cos \phi \]

Spherical to Cylindrical: \[ r = \rho \sin \phi \] \[ \theta = \theta \] \[ z = \rho \cos \phi \]

Cylindrical to Spherical: \[ \rho = \sqrt{r^2 + z^2} \] \[ \phi = \arctan \left( \frac{r}{z} \right) \] \[ \theta = \theta \]

Discrete Structures

Logic

Propositional Logic

Propositional logic deals with statements that are either true or false.

  • Negation: If ( P ) is a proposition, then the negation of ( P ) is written as ( \neg P ).
  • Conjunction: If ( P ) and ( Q ) are propositions, then the conjunction of ( P ) and ( Q ) is written as ( P \land Q ).
  • Disjunction: If ( P ) and ( Q ) are propositions, then the disjunction of ( P ) and ( Q ) is written as ( P \lor Q ).

Examples: \[ \neg P \]

\[ P \land Q \]

\[ P \lor Q \]

Truth Tables

Truth tables are used to determine the truth value of logical expressions.

Example for ( P \land Q ):

( P )( Q )( P \land Q )
TTT
TFF
FTF
FFF

Logical Laws

CategoryLaw NameLogical Expression
Identity LawsIdentity for (\land)\[ P \land \text{true} \equiv P \]
Identity for (\lor)\[ P \lor \text{false} \equiv P \]
Domination LawsDomination for (\lor)\[ P \lor \text{true} \equiv \text{true} \]
Domination for (\land)\[ P \land \text{false} \equiv \text{false} \]
Idempotent LawsIdempotent for (\lor)\[ P \lor P \equiv P \]
Idempotent for (\land)\[ P \land P \equiv P \]
Double Negation\[ \neg (\neg P) \equiv P \]
Commutative LawsCommutative for (\lor)\[ P \lor Q \equiv Q \lor P \]
Commutative for (\land)\[ P \land Q \equiv Q \land P \]
Associative LawsAssociative for (\lor)\[ (P \lor Q) \lor R \equiv P \lor (Q \lor R) \]
Associative for (\land)\[ (P \land Q) \land R \equiv P \land (Q \land R) \]
Distributive LawsDistributive of (\land) over (\lor)\[ P \land (Q \lor R) \equiv (P \land Q) \lor (P \land R) \]
Distributive of (\lor) over (\land)\[ P \lor (Q \land R) \equiv (P \lor Q) \land (P \lor R) \]
De Morgan's LawsDe Morgan for (\land)\[ \neg (P \land Q) \equiv \neg P \lor \neg Q \]
De Morgan for (\lor)\[ \neg (P \lor Q) \equiv \neg P \land \neg Q \]
Absorption LawsAbsorption for (\lor)\[ P \lor (P \land Q) \equiv P \]
Absorption for (\land)\[ P \land (P \lor Q) \equiv P \]
Negation LawsNegation of (\lor)\[ P \lor \neg P \equiv \text{true} \]
Negation of (\land)\[ P \land \neg P \equiv \text{false} \]
Propositional LawsContradiction Law\[ \neg \text{true} \equiv \text{false} \]
Tautology Law\[ \neg \text{false} \equiv \text{true} \]
Implication LawsImplication Definition\[ P \to Q \equiv \neg P \lor Q \]
Contrapositive\[ P \to Q \equiv \neg Q \to \neg P \]
Implication Identity\[ P \to P \equiv \text{true} \]
Exportation\[ (P \to (Q \to R)) \equiv ((P \land Q) \to R) \]
Hypothetical Syllogism\[ (P \to Q) \land (Q \to R) \to (P \to R) \]
Biconditional LawsBiconditional Definition\[ P \leftrightarrow Q \equiv (P \to Q) \land (Q \to P) \]
Biconditional Commutative\[ P \leftrightarrow Q \equiv Q \leftrightarrow P \]
Biconditional Associative\[ (P \leftrightarrow Q) \leftrightarrow R \equiv P \leftrightarrow (Q \leftrightarrow R) \]
Biconditional Identity\[ P \leftrightarrow P \equiv \text{true} \]
Quantifier LawsUniversal Instantiation\[ (\forall x , P(x)) \to P(c) \]
Existential Instantiation\[ (\exists x , P(x)) \to P(c) \]
Universal Generalization\[ P(c) \to (\forall x , P(x)) \]
Existential Generalization\[ P(c) \to (\exists x , P(x)) \]
Negation of Universal Quantifier\[ \neg (\forall x , P(x)) \equiv \exists x , \neg P(x) \]
Negation of Existential Quantifier\[ \neg (\exists x , P(x)) \equiv \forall x , \neg P(x) \]
Set LawsUnion with Universal Set\[ A \cup U = U \]
Intersection with Universal Set\[ A \cap U = A \]
Union with Empty Set\[ A \cup \emptyset = A \]
Intersection with Empty Set\[ A \cap \emptyset = \emptyset \]
Complement Laws\[ A \cup A' = U \]
\[ A \cap A' = \emptyset \]
Additional LawsDistributive for Quantifiers\[ \forall x (P(x) \land Q(x)) \equiv (\forall x , P(x)) \land (\forall x , Q(x)) \]
\[ \exists x (P(x) \lor Q(x)) \equiv (\exists x , P(x)) \lor (\exists x , Q(x)) \]

Sets

A set is a collection of distinct objects.

Set Operations

  • Union: The union of sets ( A ) and ( B ) is written as ( A \cup B ).
  • Intersection: The intersection of sets ( A ) and ( B ) is written as ( A \cap B ).
  • Difference: The difference of sets ( A ) and ( B ) is written as ( A - B ).

Examples: \[ A \cup B \]

\[ A \cap B \]

\[ A - B \]

Cartesian Product

The Cartesian product of sets ( A ) and ( B ) is written as ( A \times B ).

Example: \[ A \times B = { (a, b) \mid a \in A, b \in B } \]

Functions

A function ( f ) from a set ( A ) to a set ( B ) is a rule that assigns to each element of ( A ) exactly one element of ( B ).

Function Notation

If ( f ) is a function from ( A ) to ( B ), we write ( f: A \to B ).

Example: \[ f(x) = x^2 \]

Types of Functions

  • Injective (One-to-One): A function ( f ) is injective if ( f(a) = f(b) ) implies ( a = b ).
  • Surjective (Onto): A function ( f ) is surjective if for every ( b \in B ), there exists ( a \in A ) such that ( f(a) = b ).
  • Bijective: A function ( f ) is bijective if it is both injective and surjective.

Relations

A relation ( R ) from a set ( A ) to a set ( B ) is a subset of ( A \times B ).

Properties of Relations

  • Reflexive: A relation ( R ) on a set ( A ) is reflexive if ( (a, a) \in R ) for all ( a \in A ).
  • Symmetric: A relation ( R ) on a set ( A ) is symmetric if ( (a, b) \in R ) implies ( (b, a) \in R ).
  • Transitive: A relation ( R ) on a set ( A ) is transitive if ( (a, b) \in R ) and ( (b, c) \in R ) imply ( (a, c) \in R ).

Combinatorics

Basic Principles

  • Addition Principle: If there are ( n ) ways to do something and ( m ) ways to do another thing, and these two things cannot be done at the same time, then there are ( n + m ) ways to choose one of the actions.
  • Multiplication Principle: If there are ( n ) ways to do something and ( m ) ways to do another thing after that, then there are ( n \times m ) ways to do both actions.

Permutations

A permutation of a set is an arrangement of its elements in a specific order.

Example for permutations of a set with ( n ) elements: \[ P(n) = n! \]

Combinations

A combination is a selection of items from a larger pool where the order does not matter.

Example for combinations of ( n ) elements taken ( r ) at a time: \[ C(n, r) = \frac{n!}{r!(n-r)!} \]

Graph Theory

Basic Definitions

  • Graph: A graph ( G ) consists of a set of vertices ( V ) and a set of edges ( E ).
  • Directed Graph (Digraph): A graph where edges have a direction.

Types of Graphs

  • Complete Graph: A graph in which there is a unique edge between every pair of vertices.
  • Bipartite Graph: A graph whose vertices can be divided into two disjoint sets such that every edge connects a vertex in one set to a vertex in the other set.

Graph Representation

  • Adjacency Matrix: A square matrix used to represent a finite graph.
  • Adjacency List: A collection of lists or sets used to represent a graph.

Example Graph Theory Problems

Eulerian Path

An Eulerian path in a graph is a path that visits every edge exactly once.

Hamiltonian Path

A Hamiltonian path in a graph is a path that visits every vertex exactly once.

[ \text{Example Graph Theory Equations:} ]

Euler's formula for planar graphs: \[ V - E + F = 2 \]


This content covers the basics of discrete structures in computer science. Each topic includes definitions, examples, and relevant equations formatted using MathJax for mdBook.

Probability Theory

Basic Concepts

Sample Space ((S)): The set of all possible outcomes of a random experiment. \[ S = {s_1, s_2, \ldots, s_n} \]

Event ((E)): A subset of the sample space (S). \[ E \subseteq S \]

Probability of an Event ((P(E))): \[ P(E) = \frac{|E|}{|S|} ] where (|E|) is the number of outcomes in (E) and (|S|) is the number of outcomes in (S).

Axioms of Probability

  1. Non-negativity: \[ P(E) \ge 0 \]
  2. Normalization: \[ P(S) = 1 \]
  3. Additivity: For any two mutually exclusive events (A) and (B), \[ P(A \cup B) = P(A) + P(B) \]

Conditional Probability

Conditional Probability ((P(A|B))): The probability of event (A) given that event (B) has occurred. \[ P(A|B) = \frac{P(A \cap B)}{P(B)} ] provided (P(B) > 0).

Bayes' Theorem

Bayes' Theorem: \[ P(A|B) = \frac{P(B|A) P(A)}{P(B)} \]

Independent Events

Independence: Two events (A) and (B) are independent if \[ P(A \cap B) = P(A) P(B) \]

Random Variables

Random Variable ((X)): A function that assigns a numerical value to each outcome in the sample space. \[ X: S \to \mathbb{R} \]

Discrete Random Variable: A random variable that can take on a countable number of values.

Continuous Random Variable: A random variable that can take on an uncountable number of values.

Probability Distributions

Probability Mass Function (PMF) for Discrete Random Variables: \[ p_X(x) = P(X = x) \]

Probability Density Function (PDF) for Continuous Random Variables: \[ f_X(x) ] such that \[ P(a \le X \le b) = \int_a^b f_X(x) , dx \]

Cumulative Distribution Function (CDF): \[ F_X(x) = P(X \le x) \]

Expectation and Variance

Expectation (Mean) of a Discrete Random Variable: \[ \mathbb{E}[X] = \sum_x x p_X(x) \]

Expectation (Mean) of a Continuous Random Variable: \[ \mathbb{E}[X] = \int_{-\infty}^{\infty} x f_X(x) , dx \]

Variance: \[ \text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] \] \[ \text{Var}(X) = \mathbb{E}[X^2] - (\mathbb{E}[X])^2 \]

Standard Deviation: \[ \sigma_X = \sqrt{\text{Var}(X)} \]

Common Discrete Distributions

Bernoulli Distribution: \[ P(X = 1) = p, \quad P(X = 0) = 1 - p \] \[ \mathbb{E}[X] = p \] \[ \text{Var}(X) = p(1 - p) \]

Binomial Distribution: \[ P(X = k) = \binom{n}{k} p^k (1 - p)^{n - k} \] \[ \mathbb{E}[X] = np \] \[ \text{Var}(X) = np(1 - p) \]

Geometric Distribution: \[ P(X = k) = (1 - p)^{k - 1} p \] \[ \mathbb{E}[X] = \frac{1}{p} \] \[ \text{Var}(X) = \frac{1 - p}{p^2} \]

Poisson Distribution: \[ P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!} \] \[ \mathbb{E}[X] = \lambda \] \[ \text{Var}(X) = \lambda \]

Common Continuous Distributions

Uniform Distribution: \[ f_X(x) = \begin{cases} \frac{1}{b - a}, & a \le x \le b \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{a + b}{2} \] \[ \text{Var}(X) = \frac{(b - a)^2}{12} \]

Exponential Distribution: \[ f_X(x) = \begin{cases} \lambda e^{-\lambda x}, & x \ge 0 \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{1}{\lambda} \] \[ \text{Var}(X) = \frac{1}{\lambda^2} \]

Normal (Gaussian) Distribution: \[ f_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x - \mu)^2}{2\sigma^2}} \] \[ \mathbb{E}[X] = \mu \] \[ \text{Var}(X) = \sigma^2 \]

Joint Distributions

Joint Probability Mass Function (Discrete): \[ p_{X,Y}(x, y) = P(X = x, Y = y) \]

Joint Probability Density Function (Continuous): \[ f_{X,Y}(x, y) \]

Marginal Distribution: \[ p_X(x) = \sum_y p_{X,Y}(x, y) \] \[ f_X(x) = \int_{-\infty}^{\infty} f_{X,Y}(x, y) , dy \]

Conditional Distributions

Conditional PMF: \[ p_{X|Y}(x|y) = \frac{p_{X,Y}(x, y)}{p_Y(y)} \]

Conditional PDF: \[ f_{X|Y}(x|y) = \frac{f_{X,Y}(x, y)}{f_Y(y)} \]

Covariance and Correlation

Covariance: \[ \text{Cov}(X, Y) = \mathbb{E}[(X - \mathbb{E}[X])(Y - \mathbb{E}[Y])] \] \[ \text{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y] \]

Correlation Coefficient: \[ \rho_{X,Y} = \frac{\text{Cov}(X, Y)}{\sigma_X \sigma_Y} \]

Properties:

  • ( \text{Cov}(X, Y) = 0 ) implies ( X ) and ( Y ) are uncorrelated.
  • ( \rho_{X,Y} ) ranges from (-1) to (1).

Moment Generating Functions

Moment Generating Function (MGF): \[ M_X(t) = \mathbb{E}[e^{tX}] \]

Properties:

  • The ( n )-th moment of ( X ) is ( M_X^{(n)}(0) ).
  • If ( M_X(t) = M_Y(t) ), then ( X ) and ( Y ) have the same distribution.

Law of Large Numbers

Weak Law of Large Numbers: \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mathbb{E}[X] \quad \text{in probability as} \quad n \to \infty \]

Strong Law of Large Numbers: \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mathbb{E}[X] \quad \text{almost surely as} \quad n \to \infty \]

Central Limit Theorem

Central Limit Theorem: If ( X_1, X_2, \ldots, X_n ) are i.i.d. random variables with mean ( \mu ) and variance ( \sigma^2 ), then \[ \frac{\overline{X}_n - \mu}{\sigma / \sqrt{n}} \to N(0, 1) \quad \text{as} \quad n \to \infty \]

Markov and Chebyshev Inequalities

Markov's Inequality: For a non-negative random variable ( X ) and ( a > 0 ), \[ P(X \ge a) \le \frac{\mathbb{E}[X]}{a} \]

Chebyshev's Inequality: For any random variable ( X ) with mean ( \mu ) and variance ( \sigma^2 ), \[ P(|X - \mu| \ge k\sigma) \le \frac{1}{k^2} \]

Information Theory

Entropy (Discrete): \[ H(X) = -\sum_{x} p(x) \log p(x) \]

Joint Entropy: \[ H(X, Y) = -\sum_{x,y} p(x, y) \log p(x, y) \]

Conditional Entropy: \[ H(X|Y) = -\sum_{x,y} p(x, y) \log p(x|y) \]

Mutual Information: \[ I(X;Y) = H(X) + H(Y) - H(X, Y) \] \[ I(X;Y) = \sum_{x,y} p(x, y) \log \left( \frac{p(x, y)}{p(x) p(y)} \right) \]

Kullback-Leibler Divergence: \[ D_{KL}(P || Q) = \sum_{x} p(x) \log \left( \frac{p(x)}{q(x)} \right) \]

Common Transformations

Linear Transformation: If ( Y = aX + b ), then \[ \mathbb{E}[Y] = a\mathbb{E}[X] + b \] \[ \text{Var}(Y) = a^2 \text{Var}(X) \]

Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, then \[ \mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y] \] \[ \text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) \]

Convolution of Two Independent Random Variables: The PDF of the sum ( Z = X + Y ) is given by \[ f_Z(z) = \int_{-\infty}^{\infty} f_X(x) f_Y(z - x) , dx \]

Important Results

Law of Total Probability: \[ P(A) = \sum_{i} P(A|B_i) P(B_i) \] where ( {B_i} ) is a partition of the sample space.

Bayes' Theorem (General Form): \[ P(B_i|A) = \frac{P(A|B_i) P(B_i)}{\sum_{j} P(A|B_j) P(B_j)} \]

Poisson Process: A counting process with rate ( \lambda ) has:

  • Interarrival times ( T_i ) that are i.i.d. exponential with parameter ( \lambda ).
  • Number of events in time ( t ) is Poisson distributed with parameter ( \lambda t ).

Moment Generating Function (MGF): If ( X ) has an MGF ( M_X(t) ), then the ( n )-th moment is \[ \mathbb{E}[X^n] = M_X^{(n)}(0) \]

Characteristic Function: The characteristic function of ( X ) is \[ \phi_X(t) = \mathbb{E}[e^{itX}] \] and it uniquely determines the distribution of ( X ).

Stochastic Processes

Definition: A stochastic process is a collection of random variables ( {X(t) : t \in T} ) indexed by ( T ).

Markov Process: A stochastic process where the future is independent of the past given the present.

Martingale: A stochastic process ( {X_t} ) is a martingale if \[ \mathbb{E}[X_{t+1} | \mathcal{F}_t] = X_t \]

Brownian Motion: A continuous-time stochastic process ( {B(t) : t \ge 0} ) with:

  1. ( B(0) = 0 ).
  2. Independent increments.
  3. ( B(t) - B(s) \sim N(0, t-s) ) for ( 0 \le s < t ).
  4. Continuous paths.

Central Limit Theorem (CLT) for IID Random Variables

CLT Statement: If ( X_1, X_2, \ldots, X_n ) are i.i.d. random variables with mean ( \mu ) and variance ( \sigma^2 ), then \[ \frac{\overline{X}_n - \mu}{\sigma / \sqrt{n}} \to N(0, 1) \quad \text{as} \quad n \to \infty \]

Multivariate Central Limit Theorem: If ( \mathbf{X}_1, \mathbf{X}_2, \ldots, \mathbf{X}_n ) are i.i.d. random vectors with mean vector ( \mathbf{\mu} ) and covariance matrix ( \Sigma ), then \[ \sqrt{n}(\overline{\mathbf{X}}_n - \mathbf{\mu}) \to N(\mathbf{0}, \Sigma) \quad \text{as} \quad n \to \infty \]

Law of Large Numbers (LLN)

Weak Law of Large Numbers (WLLN): For i.i.d. random variables ( X_1, X_2, \ldots, X_n ) with mean ( \mu ), \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mu \quad \text{in probability as} \quad n \to \infty \]

Strong Law of Large Numbers (SLLN): For i.i.d. random variables ( X_1, X_2, \ldots, X_n ) with mean ( \mu ), \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mu \quad \text{almost surely as} \quad n \to \infty \]

Convergence in Probability and Distribution

Convergence in Probability: A sequence of random variables ( X_n ) converges in probability to ( X ) if for all ( \epsilon > 0 ), \[ \lim_{n \to \infty} P(|X_n - X| \ge \epsilon) = 0 \]

Convergence in Distribution: A sequence of random variables ( X_n ) converges in distribution to ( X ) if for all continuity points ( x ) of ( F_X(x) ), \[ \lim_{n \to \infty} F_{X_n}(x) = F_X(x) \]

Moment Generating Functions (MGF) and Characteristic Functions

MGF of Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, \[ M_{X+Y}(t) = M_X(t) M_Y(t) \]

Characteristic Function of Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, \[ \phi_{X+Y}(t) = \phi_X(t) \phi_Y(t) \]

Inequalities and Bounds

Jensen's Inequality: For a convex function ( \phi ) and random variable ( X ), \[ \phi(\mathbb{E}[X]) \le \mathbb{E}[\phi(X)] \]

Cauchy-Schwarz Inequality: For any random variables ( X ) and ( Y ), \[ (\mathbb{E}[XY])^2 \le \mathbb{E}[X^2] \mathbb{E}[Y^2] \]

Markov's Inequality: For a non-negative random variable ( X ) and ( a > 0 ), \[ P(X \ge a) \le \frac{\mathbb{E}[X]}{a} \]

Chebyshev's Inequality: For any random variable ( X ) with mean ( \mu ) and variance ( \sigma^2 ), \[ P(|X - \mu| \ge k\sigma) \le \frac{1}{k^2} \]

Bayesian Inference

Posterior Distribution: \[ P(\theta|X) = \frac{P(X|\theta) P(\theta)}{P(X)} \]

Maximum A Posteriori (MAP) Estimate: \[ \hat{\theta}{MAP} = \arg\max\theta P(\theta|X) \]

Bayesian Updating: Given a prior ( P(\theta) ) and likelihood ( P(X|\theta) ), the posterior is updated as \[ P(\theta|X) \propto P(X|\theta) P(\theta) \]

Hypothesis Testing

Null Hypothesis ((H_0)): The hypothesis that there is no effect or no difference.

Alternative Hypothesis ((H_1)): The hypothesis that there is an effect or a difference.

Test Statistic: A function of the sample data used to decide whether to reject (H_0).

p-Value: The probability of obtaining a test statistic at least as extreme as the one observed, assuming (H_0) is true.

Type I Error: Rejecting (H_0) when it is true (false positive).

Type II Error: Failing to reject (H_0) when it is false (false negative).

Significance Level ((\alpha)): The probability of making a Type I error.

Power: The probability of correctly rejecting (H_0) (1 - probability of Type II error).

Confidence Intervals

Confidence Interval for Mean ((\mu)): For a normal distribution with known variance ( \sigma^2 ), \[ \left( \overline{X} - z_{\alpha/2} \frac{\sigma}{\sqrt{n}}, \overline{X} + z_{\alpha/2} \frac{\sigma}{\sqrt{n}} \right) \] where ( z_{\alpha/2} ) is the critical value from the standard normal distribution.

Confidence Interval for Proportion ((p)): \[ \left( \hat{p} - z_{\alpha/2} \sqrt{\frac{\hat{p}(1 - \hat{p})}{n}}, \hat{p} + z_{\alpha/2} \sqrt{\frac{\hat{p}(1 - \hat{p})}{n}} \right) \] where ( \hat{p} ) is the sample proportion.

Regression Analysis

Simple Linear Regression: \[ Y = \beta_0 + \beta_1 X + \epsilon \]

Least Squares Estimates: \[ \hat{\beta}_1 = \frac{\sum (X_i - \overline{X})(Y_i - \overline{Y})}{\sum (X_i - \overline{X})^2} \] \[ \hat{\beta}_0 = \overline{Y} - \hat{\beta}_1 \overline{X} \]

Coefficient of Determination ((R^2)): \[ R^2 = \frac{\sum (\hat{Y}_i - \overline{Y})^2}{\sum (Y_i - \overline{Y})^2} \]

Multiple Linear Regression: \[ Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \cdots + \beta_p X_p + \epsilon \]

Generalized Least Squares Estimates: \[ \hat{\beta} = (X^T X)^{-1} X^T Y \]

Common Probability Distributions

Bernoulli Distribution: \[ P(X = 1) = p, \quad P(X = 0) = 1 - p \] \[ \mathbb{E}[X] = p \] \[ \text{Var}(X) = p(1 - p) \]

Binomial Distribution: \[ P(X = k) = \binom{n}{k} p^k (1 - p)^{n - k} \] \[ \mathbb{E}[X] = np \] \[ \text{Var}(X) = np(1 - p) \]

Geometric Distribution: \[ P(X = k) = (1 - p)^{k - 1} p \] \[ \mathbb{E}[X] = \frac{1}{p} \] \[ \text{Var}(X) = \frac{1 - p}{p^2} \]

Poisson Distribution: \[ P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!} \] \[ \mathbb{E}[X] = \lambda \] \[ \text{Var}(X) = \lambda \]

Uniform Distribution: \[ f_X(x) = \begin{cases} \frac{1}{b - a}, & a \le x \le b \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{a + b}{2} \] \[ \text{Var}(X) = \frac{(b - a)^2}{12} \]

Exponential Distribution: \[ f_X(x) = \begin{cases} \lambda e^{-\lambda x}, & x \ge 0 \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{1}{\lambda} \] \[ \text{Var}(X) = \frac{1}{\lambda^2} \]

Normal (Gaussian) Distribution: \[ f_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x - \mu)^2}{2\sigma^2}} \] \[ \mathbb{E}[X] = \mu \] \[ \text{Var}(X) = \sigma^2 \]

Gamma Distribution: \[ f_X(x) = \frac{\lambda^k x^{k-1} e^{-\lambda x}}{\Gamma(k)}, \quad x \ge 0 \] \[ \mathbb{E}[X] = \frac{k}{\lambda} \] \[ \text{Var}(X) = \frac{k}{\lambda^2} \]

Beta Distribution: \[ f_X(x) = \frac{x^{\alpha-1} (1 - x)^{\beta-1}}{B(\alpha, \beta)}, \quad 0 \le x \le 1 \] \[ \mathbb{E}[X] = \frac{\alpha}{\alpha + \beta} \] \[ \text{Var}(X) = \frac{\alpha\beta}{(\alpha + \beta)^2 (\alpha + \beta + 1)} \]

Chi-Square Distribution: \[ f_X(x) = \frac{1}{2^{k/2} \Gamma(k/2)} x^{k/2 - 1} e^{-x/2}, \quad x \ge 0 \] \[ \mathbb{E}[X] = k \] \[ \text{Var}(X) = 2k \]

Student's t-Distribution: \[ f_X(x) = \frac{\Gamma\left(\frac{\nu+1}{2}\right)}{\sqrt{\nu \pi} \Gamma\left(\frac{\nu}{2}\right)} \left(1 + \frac{x^2}{\nu}\right)^{-(\nu+1)/2} \] \[ \mathbb{E}[X] = 0 \quad \text{for} \quad \nu > 1 \] \[ \text{Var}(X) = \frac{\nu}{\nu-2} \quad \text{for} \quad \nu > 2 \]

Multivariate Normal Distribution: \[ f_X(\mathbf{x}) = \frac{1}{(2\pi)^{k/2} |\Sigma|^{1/2}} \exp \left( -\frac{1}{2} (\mathbf{x} - \mathbf{\mu})^T \Sigma^{-1} (\mathbf{x} - \mathbf{\mu}) \right) \] where ( \mathbf{\mu} ) is the mean vector and ( \Sigma ) is the covariance matrix.

Multinomial Distribution: \[ P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{n!}{x_1! x_2! \cdots x_k!} p_1^{x_1} p_2^{x_2} \cdots p_k^{x_k} \] where ( X_i ) is the count of the (i)-th outcome in (n) trials, and ( p_i ) is the probability of the (i)-th outcome.

Negative Binomial Distribution: \[ P(X = k) = \binom{k+r-1}{r-1} p^r (1 - p)^k \] \[ \mathbb{E}[X] = \frac{r(1 - p)}{p} \] \[ \text{Var}(X) = \frac{r(1 - p)}{p^2} \]

Hypergeometric Distribution: \[ P(X = k) = \frac{\binom{K}{k} \binom{N-K}{n-k}}{\binom{N}{n}} \] where ( X ) is the number of successes in (n) draws from a population of (N) with (K) successes.

Linear Algebra Formulas

Vectors and Vector Spaces

Vector Definition: \[ \mathbf{v} = \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} \]

Vector Addition: \[ \mathbf{u} + \mathbf{v} = \begin{pmatrix} u_1 \ u_2 \ \vdots \ u_n \end{pmatrix} + \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} = \begin{pmatrix} u_1 + v_1 \ u_2 + v_2 \ \vdots \ u_n + v_n \end{pmatrix} \]

Scalar Multiplication: \[ c \mathbf{v} = c \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} = \begin{pmatrix} c v_1 \ c v_2 \ \vdots \ c v_n \end{pmatrix} \]

Dot Product: \[ \mathbf{u} \cdot \mathbf{v} = u_1 v_1 + u_2 v_2 + \cdots + u_n v_n \] \[ \mathbf{u} \cdot \mathbf{v} = |\mathbf{u}| |\mathbf{v}| \cos \theta \]

Cross Product (in ( \mathbb{R}^3 )): \[ \mathbf{u} \times \mathbf{v} = \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\ u_1 & u_2 & u_3 \\ v_1 & v_2 & v_3 \end{vmatrix} \] \[ |\mathbf{u} \times \mathbf{v}| = |\mathbf{u}| |\mathbf{v}| \sin \theta \]

Vector Space Axioms:

  1. Closure under addition
  2. Closure under scalar multiplication
  3. Associativity of addition
  4. Commutativity of addition
  5. Existence of additive identity
  6. Existence of additive inverse
  7. Distributivity of scalar multiplication over vector addition
  8. Distributivity of scalar multiplication over field addition
  9. Compatibility of scalar multiplication with field multiplication
  10. Existence of multiplicative identity

Subspace: A subset (W) of a vector space (V) that is itself a vector space under the same operations.

Matrices

Matrix Definition: \[ A = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix} \]

Matrix Addition: \[ A + B = \begin{pmatrix} a_{11} + b_{11} & a_{12} + b_{12} & \cdots & a_{1n} + b_{1n} \ a_{21} + b_{21} & a_{22} + b_{22} & \cdots & a_{2n} + b_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} + b_{m1} & a_{m2} + b_{m2} & \cdots & a_{mn} + b_{mn} \end{pmatrix} \]

Scalar Multiplication: \[ cA = \begin{pmatrix} c a_{11} & c a_{12} & \cdots & c a_{1n} \ c a_{21} & c a_{22} & \cdots & c a_{2n} \ \vdots & \vdots & \ddots & \vdots \ c a_{m1} & c a_{m2} & \cdots & c a_{mn} \end{pmatrix} \]

Matrix Multiplication: \[ AB = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix} \begin{pmatrix} b_{11} & b_{12} & \cdots & b_{1p} \ b_{21} & b_{22} & \cdots & b_{2p} \ \vdots & \vdots & \ddots & \vdots \ b_{n1} & b_{n2} & \cdots & b_{np} \end{pmatrix} \]

Transpose: \[ A^T = \begin{pmatrix} a_{11} & a_{21} & \cdots & a_{m1} \ a_{12} & a_{22} & \cdots & a_{m2} \ \vdots & \vdots & \ddots & \vdots \ a_{1n} & a_{2n} & \cdots & a_{mn} \end{pmatrix} \]

Determinant (for a 2x2 matrix): \[ \det(A) = \begin{vmatrix} a & b \ c & d \end{vmatrix} = ad - bc \]

Inverse (for a 2x2 matrix): \[ A^{-1} = \frac{1}{\det(A)} \begin{pmatrix} d & -b \ -c & a \end{pmatrix} \]

Properties of Determinants:

  1. ( \det(A^T) = \det(A) )
  2. ( \det(AB) = \det(A) \det(B) )
  3. ( \det(A^{-1}) = \frac{1}{\det(A)} )

Systems of Linear Equations

General Form: \[ A \mathbf{x} = \mathbf{b} \]

Augmented Matrix: \[ \left( A | \mathbf{b} \right) \]

Gaussian Elimination:

  1. Form the augmented matrix.
  2. Use row operations to reach row-echelon form.
  3. Perform back-substitution to find the solution.

Row Operations:

  1. Swap two rows.
  2. Multiply a row by a non-zero scalar.
  3. Add or subtract a multiple of one row to/from another row.

Eigenvalues and Eigenvectors

Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]

Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]

Solving for Eigenvalues: Find the roots of the characteristic polynomial.

Solving for Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each eigenvalue \( \lambda \).

Diagonalization

Diagonalization of a Matrix: A matrix ( A ) is diagonalizable if there exists a matrix ( P ) such that \[ P^{-1} A P = D \] where ( D ) is a diagonal matrix.

Steps to Diagonalize a Matrix:

  1. Find the eigenvalues of ( A ).
  2. Find the eigenvectors of ( A ).
  3. Form the matrix ( P ) using the eigenvectors as columns.
  4. Form the diagonal matrix ( D ) using the eigenvalues.

Inner Product and Orthogonality

Inner Product (Dot Product): \[ \langle \mathbf{u}, \mathbf{v} \rangle = \mathbf{u} \cdot \mathbf{v} = u_1 v_1 + u_2 v_2 + \cdots + u_n v_n \]

Norm (Length) of a Vector: \[ |\mathbf{v}| = \sqrt{\langle \mathbf{v}, \mathbf{v} \rangle} \]

Orthogonality: Two vectors ( \mathbf{u} ) and ( \mathbf{v} ) are orthogonal if \[ \langle \mathbf{u}, \mathbf{v} \rangle = 0 \]

Orthogonal Projection: \[ \text{proj}_{\mathbf{u}} \mathbf{v} = \frac{\langle \mathbf{v}, \mathbf{u} \rangle}{\langle \mathbf{u}, \mathbf{u} \rangle} \mathbf{u} \]

Gram-Schmidt Process: To orthogonalize a set of vectors ( {\mathbf{v}_1, \mathbf{v}_2, \ldots, \mathbf{v}_n} ):

  1. Set ( \mathbf{u}_1 = \mathbf{v}_1 ).
  2. For ( k = 2 ) to ( n ): \[ \mathbf{u}k = \mathbf{v}k - \sum{j=1}^{k-1} \text{proj}{\mathbf{u}_j} \mathbf{v}_k \]
  3. Normalize ( \mathbf{u}_k ) to obtain orthonormal vectors ( \mathbf{e}_k = \frac{\mathbf{u}_k}{|\mathbf{u}_k|} ).

Linear Transformations

Definition: A linear transformation ( T ) from ( \mathbb{R}^n ) to ( \mathbb{R}^m ) is a function that satisfies:

  1. ( T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v}) )
  2. ( T(c \mathbf{u}) = c T(\mathbf{u}) )

Matrix Representation: If ( T(\mathbf{x}) = A \mathbf{x} ), then ( A ) is the matrix representation of ( T ).

Kernel and Image:

  • Kernel: ( \ker(T) = {\mathbf{x} \in \mathbb{R}^n : T(\mathbf{x}) = \mathbf{0}} )
  • Image: ( \text{Im}(T) = {T(\mathbf{x}) : \mathbf{x} \in \mathbb{R}^n} )

Rank-Nullity Theorem: \[ \text{dim}(\ker(T)) + \text{dim}(\text{Im}(T)) = n \]

Determinants and Inverses

Determinant (for an ( n \times n ) matrix): \[ \det(A) = \sum_{j=1}^n (-1)^{i+j} a_{ij} \det(A_{ij}) \] where ( A_{ij} ) is the ((n-1) \times (n-1)) matrix obtained by deleting the (i)-th row and (j)-th column from ( A ).

Properties of Inverses:

  1. ( (A^{-1})^{-1} = A )
  2. ( (AB)^{-1} = B^{-1}A^{-1} )
  3. ( (A^T)^{-1} = (A^{-1})^T \]

Cramer's Rule: For a system ( A \mathbf{x} = \mathbf{b} ) with ( n ) equations and ( n ) unknowns: \[ x_i = \frac{\det(A_i)}{\det(A)} \] where ( A_i ) is the matrix obtained by replacing the (i)-th column of ( A ) with ( \mathbf{b} ).

Special Matrices

Identity Matrix: \[ I = \begin{pmatrix} 1 & 0 & \cdots & 0 \ 0 & 1 & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \ 0 & 0 & \cdots & 1 \end{pmatrix} \]

Diagonal Matrix: \[ D = \begin{pmatrix} d_1 & 0 & \cdots & 0 \ 0 & d_2 & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \ 0 & 0 & \cdots & d_n \end{pmatrix} \]

Symmetric Matrix: \[ A = A^T \]

Orthogonal Matrix: \[ A^T A = A A^T = I \]

Positive Definite Matrix: A symmetric matrix ( A ) is positive definite if ( \mathbf{x}^T A \mathbf{x} > 0 ) for all non-zero vectors ( \mathbf{x} ).

Quadratic Forms

Quadratic Form: \[ Q(\mathbf{x}) = \mathbf{x}^T A \mathbf{x} \] where ( A ) is a symmetric matrix.

Classification of Quadratic Forms:

  1. Positive definite: All eigenvalues of ( A ) are positive.
  2. Negative definite: All eigenvalues of ( A ) are negative.
  3. Indefinite: Eigenvalues of ( A ) are both positive and negative.
  4. Positive semidefinite: All eigenvalues of ( A ) are non-negative.
  5. Negative semidefinite: All eigenvalues of ( A ) are non-positive.

Singular Value Decomposition (SVD)

SVD Definition: For any ( m \times n ) matrix ( A ), there exist orthogonal matrices ( U ) and ( V ) such that \[ A = U \Sigma V^T \] where ( \Sigma ) is a diagonal matrix with non-negative real numbers on the diagonal (singular values).

Properties of SVD:

  1. ( U ) and ( V ) are orthogonal matrices.
  2. ( \Sigma ) contains the singular values of ( A ).

Orthogonal Projections and Least Squares

Orthogonal Projection onto a Subspace ( W ): \[ \mathbf{p} = A (A^T A)^{-1} A^T \mathbf{b} \] where ( A ) is a matrix whose columns form a basis for ( W ).

Least Squares Solution: To solve ( A \mathbf{x} \approx \mathbf{b} ): \[ \mathbf{x} = (A^T A)^{-1} A^T \mathbf{b} \]

Eigenvalues and Eigenvectors

Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]

Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]

Solving for Eigenvalues: Find the roots of the characteristic polynomial.

Solving for Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each eigenvalue ( \lambda ).

Jordan Canonical Form

Jordan Form: A matrix ( A ) is similar to a Jordan matrix ( J ) if there exists an invertible matrix ( P ) such that \[ A = P J P^{-1} \]

Jordan Block: \[ J_k(\lambda) = \begin{pmatrix} \lambda & 1 & 0 & \cdots & 0 \ 0 & \lambda & 1 & \cdots & 0 \ \vdots & \vdots & \vdots & \ddots & \vdots \ 0 & 0 & 0 & \cdots & \lambda \end{pmatrix} \]

Steps to Find Jordan Form:

  1. Find the eigenvalues of ( A ).
  2. Find the eigenvectors and generalized eigenvectors of ( A ).
  3. Form the Jordan blocks.
  4. Form the matrix ( P ) using the eigenvectors and generalized eigenvectors.

Complex Eigenvalues and Eigenvectors

Complex Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]

Complex Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]

Solving for Complex Eigenvalues: Find the complex roots of the characteristic polynomial.

Solving for Complex Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each complex eigenvalue ( \lambda ).

Forming the Complex Matrix: Combine the real and imaginary parts of the eigenvectors to form a complex matrix.

Properties of Complex Eigenvalues:

  1. Complex eigenvalues occur in conjugate pairs.
  2. The eigenvectors corresponding to complex eigenvalues are also complex.

Matrix Exponentials

Definition: The matrix exponential of ( A ) is defined as \[ e^A = \sum_{k=0}^\infty \frac{A^k}{k!} \]

Properties:

  1. ( e^{A+B} = e^A e^B ) if ( AB = BA ).
  2. ( e^{tA} ) solves the differential equation ( \mathbf{x}' = A \mathbf{x} ) with initial condition ( \mathbf{x}(0) = \mathbf{x}_0 ).

Systems of Linear Differential Equations

General Form: \[ \mathbf{x}' = A \mathbf{x} \]

Solution Using Eigenvalues and Eigenvectors:

  1. Find the eigenvalues and eigenvectors of ( A ).
  2. Form the general solution using the eigenvalues and eigenvectors.
  3. Solve for the constants using the initial conditions.

Solution Using Matrix Exponentials: \[ \mathbf{x}(t) = e^{At} \mathbf{x}_0 \]

Diagonalizable Case: If ( A ) is diagonalizable, then \[ e^{At} = P e^{Dt} P^{-1} \] where ( D ) is a diagonal matrix containing the eigenvalues of ( A ).

Non-Diagonalizable Case: If ( A ) is not diagonalizable, use the Jordan form to compute the matrix exponential.

Differential Equations Formulas

First-Order Differential Equations

Linear First-Order Differential Equation: \[ \frac{dy}{dx} + P(x)y = Q(x) \]

Solution of Linear First-Order Differential Equation: \[ y(x) = e^{-\int P(x) , dx} \left( \int Q(x) e^{\int P(x) , dx} , dx + C \right) \]

Separable Differential Equation: \[ \frac{dy}{dx} = g(y)h(x) \]

Solution of Separable Differential Equation: \[ \int \frac{1}{g(y)} , dy = \int h(x) , dx + C \]

Exact Differential Equation: \[ M(x, y) , dx + N(x, y) , dy = 0 \]

Condition for Exactness: \[ \frac{\partial M}{\partial y} = \frac{\partial N}{\partial x} \]

Integrating Factor (for non-exact equations): \[ \mu(x) = e^{\int P(x) , dx} \] \[ \mu(y) = e^{\int Q(y) , dy} \]

Second-Order Differential Equations

Homogeneous Linear Second-Order Differential Equation: \[ a \frac{d^2y}{dx^2} + b \frac{dy}{dx} + c y = 0 \]

Characteristic Equation: \[ ar^2 + br + c = 0 \]

Solution for Distinct Real Roots ((r_1) and (r_2)): \[ y(x) = C_1 e^{r_1 x} + C_2 e^{r_2 x} \]

Solution for Repeated Roots ((r)): \[ y(x) = (C_1 + C_2 x)e^{rx} \]

Solution for Complex Roots ((\alpha \pm \beta i)): \[ y(x) = e^{\alpha x} (C_1 \cos(\beta x) + C_2 \sin(\beta x)) \]

Non-Homogeneous Linear Second-Order Differential Equation: \[ a \frac{d^2y}{dx^2} + b \frac{dy}{dx} + c y = f(x) \]

General Solution: \[ y(x) = y_h(x) + y_p(x) \]

  • (y_h(x)) is the solution to the homogeneous equation.
  • (y_p(x)) is a particular solution to the non-homogeneous equation.

Method of Undetermined Coefficients: Assume a form for (y_p(x)) based on (f(x)) and solve for coefficients.

Variation of Parameters: \[ y_p(x) = y_1(x) \int \frac{y_2(x) f(x)}{W(y_1, y_2)} , dx - y_2(x) \int \frac{y_1(x) f(x)}{W(y_1, y_2)} , dx \] where (y_1(x)) and (y_2(x)) are solutions to the corresponding homogeneous equation and (W(y_1, y_2)) is the Wronskian.

Higher-Order Differential Equations

General Linear (n)th-Order Differential Equation: \[ a_n \frac{d^n y}{dx^n} + a_{n-1} \frac{d^{n-1} y}{dx^{n-1}} + \cdots + a_1 \frac{dy}{dx} + a_0 y = f(x) \]

Solution: \[ y(x) = y_h(x) + y_p(x) \]

Systems of Differential Equations

First-Order Linear System: \[ \mathbf{X}' = A \mathbf{X} + \mathbf{B} \]

Solution Using Eigenvalues and Eigenvectors:

  1. Find eigenvalues (\lambda) and eigenvectors (\mathbf{v}) of matrix (A).
  2. General solution: \[ \mathbf{X}(t) = c_1 e^{\lambda_1 t} \mathbf{v}_1 + c_2 e^{\lambda_2 t} \mathbf{v}_2 + \cdots + c_n e^{\lambda_n t} \mathbf{v}_n \]

Phase Plane Analysis:

  • Classify critical points (nodes, saddles, spirals, centers) based on eigenvalues.

Laplace Transforms

Definition: \[ \mathcal{L}{f(t)} = \int_0^\infty e^{-st} f(t) , dt \]

Inverse Laplace Transform: \[ \mathcal{L}^{-1}{F(s)} = \frac{1}{2\pi i} \int_{\gamma - i\infty}^{\gamma + i\infty} e^{st} F(s) , ds \]

Properties:

  • Linearity: \[ \mathcal{L}{af(t) + bg(t)} = a\mathcal{L}{f(t)} + b\mathcal{L}{g(t)} \]
  • First Derivative: \[ \mathcal{L}{f'(t)} = sF(s) - f(0) \]
  • Second Derivative: \[ \mathcal{L}{f''(t)} = s^2 F(s) - sf(0) - f'(0) \]

Laplace Transform of Common Functions: \[ \mathcal{L}{1} = \frac{1}{s} \] \[ \mathcal{L}{t^n} = \frac{n!}{s^{n+1}} \] \[ \mathcal{L}{e^{at}} = \frac{1}{s-a} \] \[ \mathcal{L}{\sin(at)} = \frac{a}{s^2 + a^2} \] \[ \mathcal{L}{\cos(at)} = \frac{s}{s^2 + a^2} \]

Fourier Series

Fourier Series Representation: \[ f(x) = a_0 + \sum_{n=1}^{\infty} \left( a_n \cos \frac{n\pi x}{L} + b_n \sin \frac{n\pi x}{L} \right) \]

Coefficients: \[ a_0 = \frac{1}{2L} \int_{-L}^{L} f(x) , dx \] \[ a_n = \frac{1}{L} \int_{-L}^{L} f(x) \cos \frac{n\pi x}{L} , dx \] \[ b_n = \frac{1}{L} \int_{-L}^{L} f(x) \sin \frac{n\pi x}{L} , dx \]

Partial Differential Equations

Heat Equation: \[ \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u}{\partial x^2} \]

Wave Equation: \[ \frac{\partial^2 u}{\partial t^2} = c^2 \frac{\partial^2 u}{\partial x^2} \]

Laplace's Equation: \[ \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} = 0 \]

Poisson's Equation: \[ \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} = f(x, y) \]

Boundary and Initial Conditions

Initial Conditions:

  • (y(0) = y_0)
  • (y'(0) = y_1)

Boundary Conditions:

  • Dirichlet: (u(a, t) = 0)
  • Neumann: (\frac{\partial u}{\partial x} \bigg|_{x=a} = 0)

Separation of Variables: Assume (u(x,t) = X(x)T(t)) and separate the PDE into ODEs for (X(x)) and (T(t)).

Physics 1 Formulas

Mechanics

Kinematics Equations (for constant acceleration): \[ v = v_0 + at \] \[ s = s_0 + v_0 t + \frac{1}{2} a t^2 \] \[ v^2 = v_0^2 + 2a(s - s_0) \] \[ s = s_0 + \frac{1}{2} (v + v_0)t \]

Newton's Laws of Motion:

  1. First Law (Law of Inertia): \[ \text{An object at rest stays at rest and an object in motion stays in motion unless acted upon by an external force.} \]
  2. Second Law: \[ \mathbf{F} = m \mathbf{a} \]
  3. Third Law: \[ \text{For every action, there is an equal and opposite reaction.} \]

Gravitational Force: \[ \mathbf{F} = G \frac{m_1 m_2}{r^2} \mathbf{\hat{r}} \]

Work and Energy: \[ W = \mathbf{F} \cdot \mathbf{d} = Fd \cos \theta \] \[ K = \frac{1}{2} mv^2 \] \[ U_g = mgh \] \[ E = K + U \]

Power: \[ P = \frac{W}{t} \] \[ P = \mathbf{F} \cdot \mathbf{v} \]

Momentum: \[ \mathbf{p} = m \mathbf{v} \] \[ \mathbf{F} = \frac{d\mathbf{p}}{dt} \]

Impulse: \[ \mathbf{J} = \Delta \mathbf{p} = \int \mathbf{F} , dt \]

Collisions:

  • Elastic: Both momentum and kinetic energy are conserved.
  • Inelastic: Momentum is conserved, kinetic energy is not.

Rotational Kinematics: \[ \theta = \theta_0 + \omega_0 t + \frac{1}{2} \alpha t^2 \] \[ \omega = \omega_0 + \alpha t \] \[ \omega^2 = \omega_0^2 + 2 \alpha (\theta - \theta_0) \]

Rotational Dynamics: \[ \tau = I \alpha \] \[ L = I \omega \] \[ \mathbf{\tau} = \frac{d\mathbf{L}}{dt} \]

Moment of Inertia (for a point mass): \[ I = \sum m_i r_i^2 \]

Torque: \[ \mathbf{\tau} = \mathbf{r} \times \mathbf{F} \]

Angular Momentum: \[ \mathbf{L} = \mathbf{r} \times \mathbf{p} \]

Oscillations and Waves

Simple Harmonic Motion (SHM): \[ x(t) = A \cos(\omega t + \phi) \] \[ v(t) = -A \omega \sin(\omega t + \phi) \] \[ a(t) = -A \omega^2 \cos(\omega t + \phi) \]

Angular Frequency: \[ \omega = 2\pi f = \sqrt{\frac{k}{m}} \]

Period: \[ T = \frac{1}{f} = 2\pi \sqrt{\frac{m}{k}} \]

Wave Equation: \[ v = f \lambda \]

Standing Waves:

  • String fixed at both ends: \[ \lambda_n = \frac{2L}{n} \]
  • Open-closed tube: \[ \lambda_n = \frac{4L}{n} \]

Doppler Effect: \[ f' = f \left( \frac{v \pm v_0}{v \mp v_s} \right) \]

Thermodynamics

First Law of Thermodynamics: \[ \Delta U = Q - W \]

Work Done by a Gas: \[ W = \int P , dV \]

Ideal Gas Law: \[ PV = nRT \]

Kinetic Theory of Gases: \[ \bar{E_k} = \frac{3}{2} k_B T \]

Heat Transfer:

  • Conduction: \[ Q = \frac{kA(T_H - T_C)t}{d} \]
  • Convection: \[ Q = hA(T_s - T_f) \]
  • Radiation: \[ Q = \epsilon \sigma A T^4 \]

Second Law of Thermodynamics: \[ \text{Entropy of an isolated system always increases.} \] \[ \Delta S \ge 0 \]

Carnot Efficiency: \[ \eta = 1 - \frac{T_C}{T_H} \]

Physics 2 Formulas

Electrostatics

Coulomb's Law: \[ \mathbf{F} = k_e \frac{q_1 q_2}{r^2} \mathbf{\hat{r}} \]

Electric Field: \[ \mathbf{E} = \frac{\mathbf{F}}{q} = k_e \frac{q}{r^2} \mathbf{\hat{r}} \]

Electric Potential: \[ V = k_e \frac{q}{r} \]

Potential Energy: \[ U = qV = k_e \frac{q_1 q_2}{r} \]

Gauss's Law: \[ \oint_S \mathbf{E} \cdot d\mathbf{A} = \frac{Q_{\text{enc}}}{\epsilon_0} \]

Capacitance and Dielectrics

Capacitance: \[ C = \frac{Q}{V} \]

Parallel Plate Capacitor: \[ C = \epsilon_0 \frac{A}{d} \]

Energy Stored in a Capacitor: \[ U = \frac{1}{2} CV^2 \]

Capacitors in Series and Parallel:

  • Series: \[ \frac{1}{C_{\text{eq}}} = \sum_{i} \frac{1}{C_i} \]
  • Parallel: \[ C_{\text{eq}} = \sum_{i} C_i \]

Electric Current and Resistance

Current: \[ I = \frac{dQ}{dt} \]

Ohm's Law: \[ V = IR \]

Resistance: \[ R = \rho \frac{L}{A} \]

Power: \[ P = IV = I^2R = \frac{V^2}{R} \]

Resistors in Series and Parallel:

  • Series: \[ R_{\text{eq}} = \sum_{i} R_i \]
  • Parallel: \[ \frac{1}{R_{\text{eq}}} = \sum_{i} \frac{1}{R_i} \]

Magnetic Fields and Forces

Biot-Savart Law: \[ d\mathbf{B} = \frac{\mu_0}{4\pi} \frac{I d\mathbf{l} \times \mathbf{\hat{r}}}{r^2} \]

Ampere's Law: \[ \oint \mathbf{B} \cdot d\mathbf{l} = \mu_0 I_{\text{enc}} \]

Magnetic Force on a Moving Charge: \[ \mathbf{F} = q \mathbf{v} \times \mathbf{B} \]

Magnetic Force on a Current-Carrying Wire: \[ \mathbf{F} = I \mathbf{l} \times \mathbf{B} \]

Magnetic Flux: \[ \Phi_B = \int_S \mathbf{B} \cdot d\mathbf{A} \]

Faraday's Law of Induction: \[ \mathcal{E} = -\frac{d\Phi_B}{dt} \]

Lenz's Law: The induced emf always opposes the change in magnetic flux.

Electromagnetic Waves

Maxwell's Equations:

  1. Gauss's Law for Electricity: \[ \nabla \cdot \mathbf{E} = \frac{\rho}{\epsilon_0} \]
  2. Gauss's Law for Magnetism: \[ \nabla \cdot \mathbf{B} = 0 \]
  3. Faraday's Law of Induction: \[ \nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t} \]
  4. Ampere-Maxwell Law: \[ \nabla \times \mathbf{B} = \mu_0 \mathbf{J} + \mu_0 \epsilon_0 \frac{\partial \mathbf{E}}{\partial t} \]

Speed of Light: \[ c = \frac{1}{\sqrt{\mu_0 \epsilon_0}} \]

Wave Equation: \[ \mathbf{E} = E_0 \cos(kx - \omega t) \mathbf{\hat{y}} \] \[ \mathbf{B} = B_0 \cos(kx - \omega t) \mathbf{\hat{z}} \]

Optics

Snell's Law: \[ n_1 \sin \theta_1 = n_2 \sin \theta_2 \]

Lensmaker's Equation: \[ \frac{1}{f} = (n - 1) \left( \frac{1}{R_1} - \frac{1}{R_2} \right) \]

Magnification: \[ M = \frac{h_i}{h_o} = -\frac{d_i}{d_o} \]

Mirror and Lens Equations: \[ \frac{1}{f} = \frac{1}{d_o} + \frac{1}{d_i} \]

Modern Physics

Photoelectric Effect: \[ E = hf - \phi \] where ( E ) is the energy of the emitted electron, ( h ) is Planck's constant, ( f ) is the frequency of the incident light, and ( \phi ) is the work function.

Compton Scattering: \[ \lambda' - \lambda = \frac{h}{m_e c} (1 - \cos \theta) \]

de Broglie Wavelength: \[ \lambda = \frac{h}{p} \]

Heisenberg Uncertainty Principle: \[ \Delta x \Delta p \ge \frac{\hbar}{2} \] \[ \Delta E \Delta t \ge \frac{\hbar}{2} \]