Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

linuxutils is a suite of Linux command-line utilities written from scratch in Rust as a clean-room, permissively-licensed reimplementation of the tools traditionally provided by util-linux, plus the kernel-module tools from kmod.

Each tool aims to be a drop-in replacement for its upstream counterpart, taking the opportunity to clean up rough edges where doing so does not break existing use cases.

The project also provides ABI-compatible reimplementations of the original C libraries (libblkid, libfdisk, libmount, libsmartcols, libuuid) as shared libraries (cdylibs), so existing C/C++ code that links against them continues to work.

Project Structure

Tools are grouped into per-category crates with one cargo feature per tool, so you can install the full bundle or pick individual tools:

CrateTools
linuxutils-diskblock devices, filesystem images
linuxutils-kmodkernel module management
linuxutils-loginlogin-related utilities
linuxutils-miscmiscellaneous tools
linuxutils-schedprocess and I/O scheduling
linuxutils-systemsystem administration tools
linuxutils-termterminal-facing tools
linuxutils-texttext processing

A multicall binary (linuxutils) is also published, dispatching to any tool by argv[0] or as a subcommand — useful for container images and minimal installs.

Source Code

The source is available on GitHub.

Installing

linuxutils is currently distributed as source. Deb and Rpm packages are planned but not yet available; a Nix flake is provided.

With Cargo

You will need a recent Rust toolchain. The easiest way to install one is via rustup; the repository pins a specific toolchain via rust-toolchain.toml, which rustup will pick up automatically.

Install all tools in a category

cargo install linuxutils-disk
cargo install linuxutils-system
# ... etc.

Install a single tool

Each group crate exposes one cargo feature per tool. Disable defaults and pick the feature you want:

cargo install linuxutils-system --no-default-features --features lscpu
cargo install linuxutils-disk --no-default-features --features blockdev

Multicall binary

A single linuxutils binary that dispatches to any tool — useful for container images and minimal installs:

cargo install linuxutils
linuxutils lscpu
# or symlink: ln -s $(which linuxutils) /usr/local/bin/lscpu && lscpu

Building from source

git clone https://github.com/rustutils/linuxutils
cd linuxutils
cargo build --release

The build produces one binary per tool in target/release/, plus a multicall binary called linuxutils. Generate man pages with:

cargo xtask mangen target/man

With Nix

A flake.nix is provided at the repo root, using crane to drive the cargo build.

Individual tool binaries plus cdylibs and man pages:

nix build .#linuxutils

Multicall binary plus per-tool symlinks, cdylibs, and man pages:

nix build .#linuxutils-multicall

Development shell with cargo, rustc, clippy, rustfmt, and cargo-nextest:

nix develop

Disk

Tools for working with block devices, partition tables, and filesystem images.

Implemented

  • blockdev — call block device ioctls from the command line
  • isosize — output the length of an iso9660 filesystem

Planned

addpart, cfdisk, delpart, fdformat, fdisk, fsck, fsck.cramfs, fsck.minix, mkfs, mkfs.bfs, mkfs.cramfs, mkfs.minix, mkswap, partx, raw, resizepart, sfdisk, swaplabel.

blockdev

Call block device ioctls from the command line.

Synopsis

blockdev [-q] [-v] command [command...] device [device...]
blockdev --report [device...]

Operation

Each command performs a single ioctl on the specified block device(s). Multiple commands can be given and will be applied to each device in sequence. Set commands that take an argument consume the next positional parameter.

Report mode

--report prints a summary table for the specified devices, or all block devices from /proc/partitions if none are specified.

Columns: RO (read-only), RA (readahead), SSZ (sector size), BSZ (block size), StartSec (start sector), Size (bytes), Device.

Inputs

SourcePurpose
/dev/*Block device to operate on
/proc/partitionsEnumerate all block devices (for --report with no args)
/sys/dev/block/MAJ:MIN/startStart sector for partitions

Outputs

  • stdout: Values from get commands, report table
  • Block device ioctls for set commands

Ioctls

Get commands

CommandioctlValueReturns
--getroBLKROGET0x125eRead-only status (0 or 1)
--getbszBLKBSZGET0x80081270Block size in bytes
--getssBLKSSZGET0x1268Logical sector size
--getpbszBLKPBSZGET0x127bPhysical block size
--getsizeBLKGETSIZE0x126032-bit sector count (deprecated)
--getsize64BLKGETSIZE640x80081272Size in bytes (u64)
--getszBLKGETSIZE640x80081272Size in 512-byte sectors (getsize64/512)
--getraBLKRAGET0x1263Readahead in 512-byte sectors
--getfraBLKFRAGET0x1265Filesystem readahead
--getiominBLKIOMIN0x1278Minimum I/O size
--getiooptBLKIOOPT0x1279Optimal I/O size
--getalignoffBLKALIGNOFF0x127aAlignment offset
--getmaxsectBLKSECTGET0x1267Max sectors per request
--getdiscardzeroesBLKDISCARDZEROES0x127cDiscard zeroes support

Set commands

CommandArgumentioctlValueDescription
--setroBLKROSET0x125dSet read-only (arg=1)
--setrwBLKROSET0x125dSet read-write (arg=0)
--setbszbytesBLKBSZSET0x40081271Set block size
--setrasectorsBLKRASET0x1262Set readahead
--setfrasectorsBLKFRASET0x1264Set filesystem readahead
--flushbufsBLKFLSBUF0x1261Flush buffer cache
--rereadptBLKRRPART0x125fRe-read partition table

Command-line options

OptionDescription
-qQuiet mode
-vVerbose mode
--reportPrint summary table
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Permissions

Get commands typically work without root. Set commands, --flushbufs, and --rereadpt require root or CAP_SYS_ADMIN.

Notes

  • --setbsz is ephemeral: the block size reverts when the fd is closed.
  • --getsize is deprecated; use --getsz instead.
  • --getsz computes BLKGETSIZE64 / 512 for a 64-bit sector count.

Not yet implemented

  • --getdiskseq (requires newer kernel header)
  • --getzonesz (zoned block devices)

Kernel Modules

Tools for managing Linux kernel modules. Unlike the rest of linuxutils, these come from the kmod upstream project rather than util-linux, but are part of the standard Linux toolbox and are included here for completeness.

Implemented

(none yet)

Planned

depmod, insmod, lsmod, modinfo, modprobe, rmmod.

Login

Login-related utilities.

Implemented

  • nologin — politely refuse a login

Planned

chfn, chsh, last, login, lslogins, newgrp, runuser, su, sulogin, utmpdump, vipw.

nologin

Politely refuse a login.

Implemented

  • Display /etc/nologin.txt if it exists, otherwise a default message
  • Always exit with code 1
  • Accept and ignore all shell-compatibility flags (-c, -i, -l, --rcfile, etc.)

Miscellaneous

Tools that don’t fit cleanly into another category — calendars, file manipulation, UUID generation, locking utilities, and more.

Implemented

  • cal — display a calendar
  • copyfilerange — copy byte ranges between files
  • getopt — parse command options (enhanced)
  • kill — terminate a process
  • logger — enter messages into the system log
  • look — display lines beginning with a given string
  • lslocks — list local system locks
  • mcookie — generate magic cookies for xauth
  • namei — follow a pathname until a terminal point is found
  • rename — rename files by replacing occurrences of a string in their filenames
  • uuidgen — create a new UUID value
  • uuidparse — parse unique identifiers
  • waitpid — wait for arbitrary processes to exit
  • whereis — locate the binary, source, and manual page files for a command

Planned

blkid, enosys, exch, fincore, findfs, findmnt, getino, hardlink, lastlog2, lsblk, lsclocks, uuidd, wipefs.

cal

Display a calendar.

Implemented

  • Single month display (default)
  • Three-month display (-3)
  • Year display (-y)
  • Next twelve months (-Y)
  • N-month display (-n)
  • Monday (-m) or Sunday (-s) as first day of week
  • Julian/ordinal day numbering (-j)
  • Configurable number of columns (-c)
  • Positional arguments: [[[day] month] year]
  • Month names and abbreviations as arguments (e.g., cal March)
  • Special date words: today, tomorrow, yesterday

Not yet implemented

  • --vertical (ncal-style vertical layout)
  • --reform (Julian/Gregorian calendar reform date handling)
  • --week (ISO/US week number display)
  • --color (terminal colorization of today, weekends, headers)
  • --span (center multi-month display on the target date)
  • Locale-aware month/day names (currently English only)
  • Relative date expressions (+2days, 1 week ago)

copyfilerange

Copy byte ranges between files using copy_file_range(2).

Synopsis

copyfilerange [options] source destination range...

Operation

Copies byte ranges from a source file to a destination file using the copy_file_range(2) syscall, which can perform server-side copies and create reflinked files when the filesystem supports it.

Range format

Each range is specified as source_offset:destination_offset:length (bytes).

  • If length is 0 or omitted, copies as much data as available.
  • Omitted offsets use the last-used file position, starting at 0.
  • :: means “copy everything” (full file reflink).

Inputs

  • source — source file path
  • destination — destination file path (created if needed)
  • range... — one or more range specs as positional arguments
  • -r <file> — read range specs from a file (one per line)

Outputs

  • Destination file with copied byte ranges
  • With -v: prints each range copied

Syscalls

SyscallDescription
copy_file_range(2)Copy bytes between files (kernel-space, supports reflinks)

Command-line options

OptionDescription
-r, --ranges <file>Read range specs from file (one per line)
-v, --verbosePrint each range as it’s copied
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Notes

  • Source and destination must use the same filesystem type.
  • Some virtual filesystems (procfs, sysfs) are not supported.
  • Reflinks require filesystem support (btrfs, XFS with reflink enabled).
  • Range alignment to filesystem block size is needed for reflinks.

look

Display lines beginning with a given string, using binary search on a sorted file.

Implemented

  • Binary search lookup in sorted files
  • Default dictionary file (/usr/share/dict/words)
  • -a / --alternative: use alternate dictionary (/usr/share/dict/web2)
  • -d / --alphanum: compare only alphanumeric and blank characters
  • -f / --ignore-case: case-insensitive comparison
  • -t / --terminate: custom string termination character
  • WORDLIST environment variable support
  • Automatic -d and -f when using default dictionary

lslocks

List local system locks.

Reads /proc/locks and resolves file paths by scanning /proc/<pid>/fd/. Size is the file size (not the lock range size), matching util-linux behavior.

Known Limitations

  • Path resolution keys on (pid, inode) rather than (dev, inode) to handle btrfs subvolumes, where st_dev differs from the block device in /proc/locks. This means inodes that happen to collide across filesystems for the same pid could theoretically map to the wrong path (extremely unlikely in practice).
  • The BLOCKER and HOLDERS columns are not populated.
  • Locks held by processes without accessible /proc/<pid>/fd/ will have no path.

mcookie

Generate magic cookies (128-bit random hex values) for xauth.

Implemented

  • 128-bit random value generation from /dev/urandom
  • -f / --file: mix in additional randomness from a file (or - for stdin)
  • -m / --max-size: limit bytes read from the extra file
  • -v / --verbose: report randomness sources to stderr

uuidgen

Create new UUID values.

Implemented

  • -r / --random: random-based UUID (v4, default)
  • -t / --time: time-based UUID (v1)
  • -6 / --time-v6: reordered time-based UUID (v6)
  • -7 / --time-v7: Unix epoch time-based UUID (v7)
  • -m / --md5: MD5 name-based UUID (v3)
  • -s / --sha1: SHA1 name-based UUID (v5)
  • -n / --namespace: namespace UUID or alias (@dns, @url, @oid, @x500)
  • -N / --name: name string to hash
  • -C / --count: generate multiple UUIDs
  • -x / --hex: interpret name as hex string

uuidparse

Parse and display information about UUIDs.

Implemented

  • Parse UUIDs from arguments or stdin
  • -J / --json: JSON output
  • -n / --noheadings: suppress header line
  • -o / --output: select columns (UUID, VARIANT, TYPE, TIME)
  • -r / --raw: raw output format
  • Variant detection (NCS, DCE, Microsoft, other)
  • Type detection (nil, time-based, DCE, name-based, random, sha1-based, v6, v7)
  • Timestamp extraction from time-based UUIDs

waitpid

Wait for arbitrary (non-child) processes to exit.

Uses pidfd_open(2) and poll(2) to monitor processes without requiring a parent-child relationship.

Implemented

  • Wait for one or more PIDs to exit
  • -v / --verbose: report when each PID exits
  • -t / --timeout: maximum wait time in seconds (exit code 3 on timeout)
  • -e / --exited: silently ignore already-exited PIDs
  • -c / --count: exit after N processes have exited (default: all)

Exit codes

  • 0: all (or --count) processes exited
  • 1: general failure
  • 2: system doesn’t support pidfd (ENOSYS)
  • 3: timeout expired

Scheduling

Tools for manipulating process and I/O scheduling attributes.

Implemented

  • chrt — manipulate the real-time attributes of a process
  • ionice — set or get process I/O scheduling class and priority
  • taskset — set or retrieve a process’s CPU affinity

Planned

coresched, uclampset.

System

System administration tools — kernel ring buffer, IPC, namespaces, swap, loop devices, resource limits, and CPU/memory introspection.

Implemented

  • blkdiscard — discard sectors on a block device
  • choom — display and adjust OOM-killer score
  • ctrlaltdel — set the function of the Ctrl-Alt-Del combination
  • dmesg — print or control the kernel ring buffer
  • eject — eject removable media
  • fadvise — advise the kernel about file access patterns
  • fallocate — preallocate or deallocate space to a file
  • flock — manage locks from shell scripts
  • fsfreeze — suspend or resume access to a filesystem
  • fstrim — discard unused blocks on a mounted filesystem
  • ipcmk — create System V IPC resources
  • ipcrm — remove System V IPC resources
  • ipcs — show information on System V IPC facilities
  • losetup — set up and control loop devices
  • lscpu — display information about the CPU architecture
  • lsipc — list information on IPC facilities
  • lsirq — display kernel interrupt information
  • lsmem — list memory ranges with their online status
  • lsns — list system namespaces
  • mountpoint — see if a directory or file is a mountpoint
  • nsenter — run a program in different namespaces
  • pipesz — set or examine pipe and FIFO buffer sizes
  • pivot_root — change the root filesystem
  • prlimit — get and set process resource limits
  • renice — alter priority of running processes
  • rfkill — enable and disable wireless devices
  • setpgid — run a program in a new process group
  • setsid — run a program in a new session
  • swapoff — disable devices and files for paging and swapping
  • swapon — enable devices and files for paging and swapping
  • unshare — run a program in new namespaces

Planned

adjtime_config, blkpr, blkzone, chcpu, chmem, hwclock, irqtop, ldattach, mount, readprofile, rtcwake, setarch, setpriv, switch_root, tunelp, umount, wdctl, zramctl.

blkdiscard

Discard sectors on a block device.

Synopsis

blkdiscard [options] device

Operation

Sends a discard, secure discard, or zero-out command to a block device. This tells the storage device that a range of blocks is no longer in use and can be reclaimed (for SSDs) or zeroed (for thin provisioning).

By default, discards the entire device in one ioctl call. With --step, breaks the operation into chunks.

Inputs

SourcePurpose
Block device pathTarget device
BLKGETSIZE64 ioctlGet device size for default length
BLKSSZGET ioctlGet sector size for alignment validation

Outputs

  • BLKDISCARD / BLKSECDISCARD / BLKZEROOUT ioctl on the device

Ioctls

IoctlValueArgumentUsed when
BLKDISCARD0x1277u64[2] = [offset, length]Default mode
BLKSECDISCARD0x127du64[2] = [offset, length]--secure
BLKZEROOUT0x127fu64[2] = [offset, length]--zeroout
BLKGETSIZE640x80081272u64Get device size
BLKSSZGET0x1268intGet sector size

Command-line options

OptionDescription
-f, --forceDisable O_EXCL exclusive mode
-o, --offset <N>Byte offset to start (default: 0, must be sector-aligned)
-l, --length <N>Number of bytes to discard (default: to end of device)
-p, --step <N>Bytes per ioctl iteration (default: all at once)
-q, --quietSuppress warnings
-s, --secureSecure discard (BLKSECDISCARD)
-z, --zerooutZero-fill (BLKZEROOUT)
-v, --verboseShow progress
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure
2Device does not support discard

Permissions

Requires write access to the block device (typically root).

Notes

  • All data in the discarded range is permanently destroyed.
  • Offset and length must be aligned to the device sector size.
  • --secure and --zeroout are mutually exclusive.
  • Device is opened with O_EXCL by default to prevent collisions with mounted filesystems. Use --force to override.

ctrlaltdel

Set the function of the Ctrl-Alt-Del key combination.

Synopsis

ctrlaltdel [hard|soft]

Operation

  • No argument: Reads /proc/sys/kernel/ctrl-alt-del and prints hard (1) or soft (0).
  • hard: Writes 1 to /proc/sys/kernel/ctrl-alt-del. Ctrl-Alt-Del will immediately reboot the system without syncing.
  • soft: Writes 0 to /proc/sys/kernel/ctrl-alt-del. Ctrl-Alt-Del will send SIGINT to PID 1 (init), which handles a graceful shutdown.

Equivalent to calling reboot(2) with LINUX_REBOOT_CMD_CAD_ON (hard) or LINUX_REBOOT_CMD_CAD_OFF (soft), but uses /proc/sys/kernel/ctrl-alt-del for simplicity.

Inputs

  • /proc/sys/kernel/ctrl-alt-del — read to query current state

Outputs

  • /proc/sys/kernel/ctrl-alt-del — written to change state
  • stdout: prints hard or soft when querying

Command-line options

OptionDescription
hardSet Ctrl-Alt-Del to immediately reboot
softSet Ctrl-Alt-Del to send SIGINT to init
(none)Display current setting
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure (permission denied, invalid argument)

Permissions

Requires root (or CAP_SYS_ADMIN) to change the setting. Querying is available to any user who can read /proc/sys/kernel/ctrl-alt-del.

eject

Eject removable media.

Synopsis

eject [options] [device|mountpoint]

Operation

Ejects removable media (CD-ROM, USB drives, etc.) by trying multiple eject methods in sequence until one succeeds. Automatically unmounts the device (and its partitions) before ejecting.

Eject methods (tried in order)

  1. CD-ROM (-r): CDROMEJECT ioctl (0x5309)
  2. SCSI (-s): SG_IO ioctl with SCSI START_STOP command (works for USB mass storage)
  3. Floppy (-f): FDEJECT ioctl
  4. Tape (-q): MTIOCTOP with MTOFFL

If a specific method is requested via flags, only that method is tried.

Tray operations

  • --trayclose (-t): Close tray via CDROMCLOSETRAY (0x5319)
  • --traytoggle (-T): Query status via CDROM_DRIVE_STATUS (0x5326), then close or open accordingly

Lock/unlock

  • --manualeject on: Lock hardware eject button via CDROM_LOCKDOOR (0x5329, arg=1)
  • --manualeject off: Unlock via CDROM_LOCKDOOR (arg=0)

Inputs

SourcePurpose
Device argument or /dev/cdromTarget device to eject
/proc/mountsFind mounted filesystems for auto-unmount
/sys/block/*/devResolve partitions to whole disk

Outputs

  • Device ioctls to eject/close/lock media
  • Calls umount(8) to unmount before ejecting

Ioctls

IoctlValueDescription
CDROMEJECT0x5309Eject CD-ROM media
CDROMCLOSETRAY0x5319Close CD-ROM tray
CDROM_LOCKDOOR0x5329Lock/unlock hardware eject button
CDROM_DRIVE_STATUS0x5326Query tray open/closed status
SG_IO0x2285Send SCSI commands (START_STOP for eject)
FDEJECT0x025aEject floppy disk

SCSI commands (via SG_IO)

CommandOpcodeDescription
ALLOW_MEDIUM_REMOVAL0x1eUnlock media before eject
START_STOP0x1bLoEj=1, Start=0 → eject media

Command-line options

OptionDescription
-a, --auto <on|off>Toggle auto-eject mode
-c, --changerslot <N>Select CD changer slot
-d, --defaultDisplay default device name
-F, --forceForce eject, skip device type check
-f, --floppyUse floppy eject method
-i, --manualeject <on|off>Lock/unlock hardware eject button
-M, --no-partitions-unmountDon’t unmount other partitions
-m, --no-unmountDon’t unmount at all
-n, --noopShow device but take no action
-p, --procUse /proc/mounts instead of /etc/mtab
-q, --tapeUse tape drive offline command
-r, --cdromUse CD-ROM eject command
-s, --scsiUse SCSI eject commands
-T, --traytoggleToggle tray open/close
-t, --traycloseClose CD-ROM tray
-v, --verboseVerbose output
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Permissions

Requires sufficient permissions to open the device (typically root or membership in cdrom/disk group).

Not yet implemented

  • -X, --listspeed (list CD-ROM speeds)
  • -x, --cdspeed (set CD-ROM speed)
  • -c, --changerslot (CD changer slot selection)
  • -a, --auto (auto-eject mode)
  • UUID= / LABEL= device specifiers
  • Partition-to-whole-disk resolution via sysfs

fadvise

Advise the kernel about file access patterns via posix_fadvise(2).

Synopsis

fadvise [options] filename
fadvise [options] -d file-descriptor

Operation

Calls posix_fadvise(2) to advise the kernel about expected access patterns for a file. Most commonly used with dontneed to drop a file’s pages from the page cache.

Inputs

  • filename — file to advise on
  • -d fd — file descriptor number (for already-open files in scripts)

Outputs

None (the syscall has no visible output).

Syscalls

SyscallDescription
posix_fadvise(2)Declare access pattern for file data

Advice values

ValueDescription
normalNo special access pattern (default kernel behavior)
sequentialData will be accessed sequentially
randomData will be accessed randomly
noreuseData will be accessed once
willneedData will be needed soon (prefetch)
dontneedData will not be needed soon (drop from cache) — default

Command-line options

OptionDescription
-a, --advice <advice>Advice to apply (default: dontneed)
-o, --offset <bytes>Beginning offset (default: 0)
-l, --length <bytes>Length of range (default: 0 = to end of file)
-d, --fd <N>Operate on file descriptor N instead of a filename
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

flock

Manage locks from shell scripts.

Acquires a flock(2) lock on a file or directory and optionally runs a command while holding it, or operates on an already-open file descriptor.

Not Implemented

  • --fcntl (F_OFD_SETLK/F_OFD_SETLKW open file description locks)

fsfreeze

Suspend or resume access to a filesystem.

Synopsis

fsfreeze --freeze <mountpoint>
fsfreeze --unfreeze <mountpoint>

Operation

  • --freeze: Suspends all new writes to the filesystem, flushes all dirty data/metadata/log to disk, and blocks any process that attempts to write until unfrozen. Uses the FIFREEZE ioctl.
  • --unfreeze: Resumes normal filesystem operations and unblocks waiting writers. Uses the FITHAW ioctl.

Inputs

  • <mountpoint> — path to a mounted filesystem directory

Outputs

None. The tool operates purely via ioctls on the mountpoint.

Syscalls / ioctls

ioctlValueDescription
FIFREEZE0xc0045877Freeze filesystem (halt writes, flush to disk)
FITHAW0xc0045878Thaw (unfreeze) filesystem

Both ioctls take an int argument of 0.

Command-line options

OptionDescription
-f, --freezeFreeze the filesystem
-u, --unfreezeUnfreeze the filesystem
-h, --helpDisplay help
-V, --versionDisplay version

Exactly one of --freeze or --unfreeze must be specified.

Exit codes

CodeMeaning
0Success
1Failure (permission denied, not a mountpoint, ioctl error)

Permissions

Requires root privileges.

Supported filesystems

btrfs, ext2/3/4, f2fs, jfs, nilfs2, reiserfs, xfs.

Notes

  • The filesystem must be mounted.
  • Device-mapper (LVM) automatically freezes/thaws on snapshot creation; manual freeze is unnecessary.
  • Useful for creating consistent backups of the underlying block device.

fstrim

Discard unused blocks on a mounted filesystem (TRIM/UNMAP for SSDs and thin-provisioned storage).

Synopsis

fstrim [-v] [-o offset] [-l length] [-m minimum-size] mountpoint
fstrim [-v] -a|-A [-t types]

Operation

Sends the FITRIM ioctl to the filesystem, which tells the underlying block device that certain blocks are no longer in use and may be reclaimed. This is essential for SSD wear leveling and thin-provisioned storage reclamation.

Single mountpoint mode

Trims the specified mounted filesystem with the given offset, length, and minimum free extent size parameters.

Batch modes

  • --all (-a): Enumerates all mounted filesystems from /proc/self/mountinfo and trims each that supports discard. Errors from unsupported filesystems are silently ignored.
  • --fstab (-A): Reads /etc/fstab, filters to only currently mounted filesystems, and trims those. Entries with mount option X-fstrim.notrim are skipped. Falls back to kernel command line for root filesystem if not in fstab.

Inputs

SourceUsed byPurpose
<mountpoint>Single modeDirectory to trim
/proc/self/mountinfo--allEnumerate mounted filesystems
/etc/fstab--fstabFilter filesystems to trim

Outputs

  • stdout: With --verbose, prints bytes trimmed per filesystem (e.g. /: 1.5 GiB (1610612736 bytes) trimmed)

Syscalls / ioctls

ioctlValueDescription
FITRIM0xc0185879Discard unused blocks

The ioctl takes a struct fstrim_range:

struct fstrim_range {
    __u64 start;   // byte offset (from --offset, default 0)
    __u64 len;     // byte length (from --length, default ULLONG_MAX)
    __u64 minlen;  // minimum extent length (from --minimum, default 0)
};

On return, the kernel updates len to the number of bytes actually discarded.

Command-line options

OptionDescription
-a, --allTrim all mounted filesystems that support discard
-A, --fstabTrim all mounted filesystems listed in /etc/fstab
-o, --offset <num>Byte offset to start trimming (default: 0)
-l, --length <num>Number of bytes to trim (default: entire filesystem)
-m, --minimum <num>Minimum contiguous free range to discard (default: 0)
-t, --types <list>Comma-separated filesystem type filter (prefix no to exclude)
-v, --verbosePrint number of discarded bytes
-n, --dry-runDo everything except the actual FITRIM ioctl
--quiet-unsupportedSuppress errors when trim is unsupported
-h, --helpDisplay help
-V, --versionDisplay version

Numeric arguments accept size suffixes: KiB, MiB, GiB, TiB (1024-based) and KB, MB, GB, TB (1000-based).

Exit codes

CodeMeaning
0Success
1Failure (single mountpoint mode)
32All failed (batch mode)
64Some succeeded, some failed (batch mode)

Permissions

Requires root privileges (the FITRIM ioctl requires CAP_SYS_ADMIN).

Notes

  • The autofs filesystem type is excluded by default in batch modes.
  • X-fstrim.notrim mount option in /etc/fstab prevents trimming (only with --fstab).
  • Commonly run via a systemd timer (fstrim.timer) on a weekly basis.

Not yet implemented

  • --listed-in (custom source files)
  • Size suffix parsing (numeric args are plain bytes only)
  • --quiet-unsupported

ipcmk

Create System V IPC resources.

Synopsis

ipcmk -M <size>     # create shared memory segment
ipcmk -Q            # create message queue
ipcmk -S <nsems>    # create semaphore array

Operation

Creates System V IPC resources using shmget(2), msgget(2), or semget(2) with IPC_PRIVATE as the key (guaranteeing a new unique resource).

Syscalls

SyscallFlagDescription
shmget(IPC_PRIVATE, size, IPC_CREAT | mode)-MCreate shared memory
msgget(IPC_PRIVATE, IPC_CREAT | mode)-QCreate message queue
semget(IPC_PRIVATE, nsems, IPC_CREAT | mode)-SCreate semaphore array

Command-line options

OptionDescription
-M, --shmem <size>Create shared memory segment of given size
-Q, --queueCreate message queue
-S, --semaphore <N>Create semaphore array with N elements
-p, --mode <mode>Permissions in octal (default: 0644)
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Not yet implemented

  • POSIX IPC (-m, -q, -s with -n name)
  • Size suffix parsing (KiB, MiB, GiB)

ipcrm

Remove System V IPC resources.

Synopsis

ipcrm -m <shmid>       # remove shared memory by ID
ipcrm -M <key>         # remove shared memory by key
ipcrm -q <msqid>       # remove message queue by ID
ipcrm -Q <key>         # remove message queue by key
ipcrm -s <semid>       # remove semaphore by ID
ipcrm -S <key>         # remove semaphore by key
ipcrm -a [type]        # remove all

Operation

Removes System V IPC resources using shmctl(2), msgctl(2), or semctl(2) with IPC_RMID.

For key-based removal, first resolves the key to an ID via the corresponding *get() syscall, then removes by ID.

Syscalls

SyscallDescription
shmctl(id, IPC_RMID, NULL)Mark shared memory for removal
msgctl(id, IPC_RMID, NULL)Remove message queue immediately
semctl(id, 0, IPC_RMID)Remove semaphore array immediately
shmget(key, 0, 0)Resolve key to shmid
msgget(key, 0)Resolve key to msqid
semget(key, 0, 0)Resolve key to semid

Command-line options

OptionDescription
-m, --shmem-id <id>Remove shared memory by ID
-M, --shmem-key <key>Remove shared memory by key
-q, --queue-id <id>Remove message queue by ID
-Q, --queue-key <key>Remove message queue by key
-s, --semaphore-id <id>Remove semaphore by ID
-S, --semaphore-key <key>Remove semaphore by key
-a, --all[=shm|msg|sem]Remove all (optionally filtered)
-v, --verboseVerbose output
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Notes

  • Shared memory removal only takes effect after all attached processes detach.
  • Message queue and semaphore removal is immediate.
  • Keys/IDs accept decimal, hex (0x prefix), or octal (0 prefix).

Not yet implemented

  • POSIX IPC removal
  • Legacy syntax (ipcrm shm|msg|sem <id>...)

ipcs

Show information on System V IPC facilities.

Synopsis

ipcs [-m] [-q] [-s] [-a]
ipcs -l
ipcs -u
ipcs -i <id> {-m|-q|-s}

Operation

Reads /proc/sysvipc/{shm,msg,sem} to display information about active System V IPC resources.

Inputs

SourcePurpose
/proc/sysvipc/shmShared memory segments
/proc/sysvipc/msgMessage queues
/proc/sysvipc/semSemaphore arrays
/proc/sys/kernel/shm*Shared memory limits
/proc/sys/kernel/msg*Message queue limits
/proc/sys/kernel/semSemaphore limits

Command-line options

OptionDescription
-m, --shmemsShow shared memory segments
-q, --queuesShow message queues
-s, --semaphoresShow semaphore arrays
-a, --allShow all three (default)
-l, --limitsShow system resource limits
-u, --summaryShow usage summary
-c, --creatorShow creator and owner
-p, --pidShow PIDs of creator and last operator
-t, --timeShow time information
-i, --id <id>Show details for one resource (with -m/-q/-s)
-b, --bytesShow sizes in bytes
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Not yet implemented

  • -i <id> single resource detail view
  • -c creator/owner view
  • -p PID view
  • -t time view
  • --human human-readable sizes

losetup

Set up and control loop devices.

Synopsis

losetup [loopdev]                           # show status of one device
losetup [-a] [-l]                           # list all used devices
losetup -f [--show] [-o offset] [file]      # find free device (optionally set up)
losetup [-o offset] [--sizelimit N] loopdev file  # set up loop device
losetup -d loopdev...                       # detach one or more devices
losetup -D                                  # detach all devices
losetup -j file                             # find devices associated with file
losetup -c loopdev                          # resize (reread backing file size)

Operation modes

List / query

  • No arguments or -a: Lists all active loop devices.
  • loopdev only: Shows info for a single device via LOOP_GET_STATUS64.
  • -j file: Finds all loop devices backed by the given file (scans sysfs).

Setup

  • loopdev file: Associates the loop device with the backing file.
  • -f file: Finds a free loop device via LOOP_CTL_GET_FREE, then sets it up.
  • Uses LOOP_SET_FD to associate, then LOOP_SET_STATUS64 to configure offset/sizelimit/flags.

Detach

  • -d loopdev...: Detaches one or more devices via LOOP_CLR_FD.
  • -D: Detaches all active loop devices.

Resize

  • -c loopdev: Tells the kernel to reread the backing file size via LOOP_SET_CAPACITY.

Inputs

SourcePurpose
/dev/loop-controlLOOP_CTL_GET_FREE ioctl to find free devices
/dev/loopNIoctls to set up, query, detach, resize
/sys/block/loopN/loop/backing_fileRead backing file path for listing
/sys/block/loopN/loop/offsetRead offset for listing
/sys/block/loopN/loop/sizelimitRead size limit for listing
/sys/block/loopN/loop/autoclearRead autoclear flag
/sys/block/loopN/loop/partscanRead partscan flag
/sys/block/loopN/loop/dioRead direct-io flag
/sys/block/loopN/roRead read-only status

Outputs

  • stdout: Device info in various formats (old-style -a, tabular --list)
  • /dev/loopN: Created/configured/detached via ioctls

Ioctls

IoctlValueTargetDescription
LOOP_SET_FD0x4C00/dev/loopNAssociate with backing file fd
LOOP_CLR_FD0x4C01/dev/loopNDetach (disassociate)
LOOP_SET_STATUS640x4C04/dev/loopNSet offset, sizelimit, flags
LOOP_GET_STATUS640x4C05/dev/loopNGet current status
LOOP_SET_CAPACITY0x4C07/dev/loopNReread backing file size
LOOP_CTL_GET_FREE0x4C82/dev/loop-controlFind free loop device number

Data structure: loop_info64

lo_device:           u64  (backing device, read-only)
lo_inode:            u64  (backing inode, read-only)
lo_rdevice:          u64  (read-only)
lo_offset:           u64  (byte offset into backing file)
lo_sizelimit:        u64  (0 = use entire file)
lo_number:           u32  (device number, read-only)
lo_encrypt_type:     u32  (obsolete)
lo_encrypt_key_size: u32  (obsolete)
lo_flags:            u32  (LO_FLAGS_*)
lo_file_name:        [u8; 64]  (reference string)
lo_crypt_name:       [u8; 64]  (obsolete)
lo_encrypt_key:      [u8; 32]  (obsolete)
lo_init:             [u64; 2]  (reserved)

Flags

FlagValueDescription
LO_FLAGS_READ_ONLY1Read-only device
LO_FLAGS_AUTOCLEAR4Auto-destroy on last close
LO_FLAGS_PARTSCAN8Auto partition scanning
LO_FLAGS_DIRECT_IO16Direct I/O to backing file

Command-line options

OptionDescription
-a, --allList all used devices
-d, --detachDetach one or more devices
-D, --detach-allDetach all used devices
-f, --findFind first unused device
-c, --set-capacityResize loop device
-j, --associated <file>List devices associated with file
-o, --offset <N>Start at byte offset into file
--sizelimit <N>Limit device size in bytes
-b, --sector-size <N>Set logical sector size (512-pagesize, power of 2)
-P, --partscanForce kernel partition table scan
-r, --read-onlySet up read-only
--showPrint device name after setup (with -f)
-l, --listTabular list format
-n, --noheadingsSuppress headers in list output
-v, --verboseVerbose mode
-J, --jsonJSON output format
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Device not configured (query mode)
2Error determining device status

Permissions

Setting up, detaching, and resizing loop devices requires root or CAP_SYS_ADMIN. Listing via sysfs is available to any user.

Not yet implemented

  • --direct-io flag
  • --loop-ref reference string
  • --nooverlap (-L)
  • --output column selection
  • --output-all
  • --raw output format
  • JSON output (-J)
  • Size suffix parsing for offset/sizelimit
  • LOOP_CONFIGURE atomic setup (Linux 5.8+)

lscpu

Display information about the CPU architecture.

Synopsis

lscpu [options]

Operation

Gathers CPU information from /proc/cpuinfo and /sys/devices/system/cpu/ and displays it as key-value pairs (default), per-CPU table (--extended), or cache detail table (--caches).

Inputs

SourcePurpose
/proc/cpuinfoCPU model, vendor, family, flags, bugs, bogomips
/sys/devices/system/cpu/onlineOnline CPU list
/sys/devices/system/cpu/offlineOffline CPU list
/sys/devices/system/cpu/cpu<N>/topology/core_idPhysical core ID
/sys/devices/system/cpu/cpu<N>/topology/physical_package_idSocket ID
/sys/devices/system/cpu/cpu<N>/cache/index<M>/levelCache level
/sys/devices/system/cpu/cpu<N>/cache/index<M>/typeCache type
/sys/devices/system/cpu/cpu<N>/cache/index<M>/sizeCache size
/sys/devices/system/cpu/cpu<N>/cache/index<M>/shared_cpu_listCPUs sharing cache
/sys/devices/system/cpu/cpu<N>/cpufreq/cpuinfo_max_freqMax frequency
/sys/devices/system/cpu/cpu<N>/cpufreq/cpuinfo_min_freqMin frequency
/sys/devices/system/node/node<N>/cpulistNUMA node CPU mapping
/sys/devices/system/cpu/vulnerabilities/*CPU vulnerability status

Command-line options

OptionDescription
-e, --extended[=list]Extended per-CPU table
-C, --caches[=list]Cache information table
-J, --jsonJSON output
-B, --bytesShow sizes in bytes
-h, --helpDisplay help
-V, --versionDisplay version

Default output fields

  • Architecture, CPU op-mode(s), Address sizes, Byte Order
  • CPU(s), On-line/Off-line CPU(s) list
  • Vendor ID, Model name, CPU family, Model, Stepping
  • Thread(s) per core, Core(s) per socket, Socket(s)
  • CPU max/min MHz, BogoMIPS
  • Flags, Virtualization
  • L1d/L1i/L2/L3 cache (with instance count)
  • NUMA node(s), NUMA node CPU mapping
  • Vulnerabilities

Exit codes

CodeMeaning
0Success
1Failure

Not yet implemented

  • -e extended per-CPU table
  • -C cache detail table
  • -p parsable output
  • -J JSON output
  • -s sysroot
  • -x hex masks
  • -y physical IDs
  • --hierarchic subsections
  • -a/-b/-c online/offline filtering
  • --output-all
  • --raw

lsipc

List information on IPC facilities.

Synopsis

lsipc              # show global summary
lsipc -m           # list shared memory segments
lsipc -q           # list message queues
lsipc -s           # list semaphore arrays
lsipc -g [-m|-q|-s] # show system-wide limits and usage

Operation

Modern replacement for ipcs. Reads /proc/sysvipc/* and /proc/sys/kernel/* to display IPC resource information.

Inputs

SourcePurpose
/proc/sysvipc/shmShared memory segments
/proc/sysvipc/msgMessage queues
/proc/sysvipc/semSemaphore arrays
/proc/sys/kernel/shm{max,all,mni}Shared memory limits
/proc/sys/kernel/msg{max,mnb,mni}Message queue limits
/proc/sys/kernel/semSemaphore limits

Command-line options

OptionDescription
-m, --shmemsList shared memory segments
-q, --queuesList message queues
-s, --semaphoresList semaphore arrays
-g, --globalShow system-wide usage and limits
--noheadingsSuppress table headers
-b, --bytesShow sizes in bytes
-J, --jsonJSON output
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Incorrect arguments
2Serious error

Not yet implemented

  • POSIX IPC listing (-M, -Q, -S)
  • -i <id> single resource detail
  • -N <name> POSIX resource detail
  • -o column selection
  • --raw, --export, --newline output formats
  • --time, --time-format time display
  • -c creator info
  • -J JSON output

lsirq

Display kernel interrupt information.

Implemented

  • Parse /proc/interrupts and /proc/softirqs
  • -J / --json: JSON output
  • -P / --pairs: key=“value” output
  • -n / --noheadings: suppress header
  • -o / --output: select columns (IRQ, TOTAL, NAME)
  • -s / --sort: sort by column
  • -S / --softirq: show softirqs instead of hardware interrupts
  • -t / --threshold: filter by minimum count (supports K/M/G suffixes)
  • -C / --cpu-list: filter by CPU (comma-separated, ranges supported)
  • Default sort by TOTAL descending

lsmem

List the ranges of available memory with their online status.

Implemented

  • Read memory blocks from /sys/devices/system/memory/
  • Merge contiguous blocks with matching attributes into ranges
  • -a / --all: list each individual memory block
  • -b / --bytes: print sizes in bytes
  • -J / --json: JSON output
  • -P / --pairs: key=“value” output
  • -r / --raw: raw output
  • -n / --noheadings: suppress header
  • -o / --output: select columns (RANGE, SIZE, STATE, REMOVABLE, BLOCK, NODE, ZONES)
  • --output-all: show all columns
  • -S / --split: control range merging by attribute (state, removable, node, zones, or “none”)
  • -s / --sysroot: alternative system root
  • --summary: summary line control (never, always, only)
  • NUMA node detection
  • Memory zone detection

lsns

List system namespaces.

Scans /proc/*/ns/ to discover namespaces and aggregates process counts.

Implemented

  • List all namespaces with type, process count, lowest PID, user, and command
  • -J / --json: JSON output
  • -r / --raw: raw output
  • -n / --noheadings: suppress header
  • -o / --output: select columns (NS, TYPE, NPROCS, PID, PPID, COMMAND, UID, USER)
  • --output-all: show all columns
  • -t / --type: filter by namespace type (mnt, net, ipc, user, pid, uts, cgroup, time)
  • -p / --task: show namespaces for a specific PID
  • Positional namespace inode filter

Not yet implemented

  • -l / --list: list format (currently the default)
  • -P / --persistent: show namespaces without processes
  • -Q / --filter: display filter expressions
  • -u / --notruncate: don’t truncate text
  • -W / --nowrap: no multi-line representation
  • -T / --tree: tree format (parent, owner, or process)
  • NETNSID, NSFS, PNS, ONS columns

mountpoint

Check if a directory or file is a mountpoint.

Implemented

  • Check via /proc/self/mountinfo with stat fallback
  • -d / --fs-devno: print major:minor device number of the filesystem
  • -q / --quiet: suppress all output
  • -x / --devno: print major:minor of the block device
  • --nofollow: don’t follow symlinks
  • Exit code 0 for mountpoints, 32 otherwise

pipesz

Set or examine pipe and FIFO buffer sizes.

Synopsis

pipesz [options] --get
pipesz [options] --set <size> [--] [command [args...]]

Operation

Uses fcntl(2) with F_GETPIPE_SZ / F_SETPIPE_SZ to get or set the internal buffer sizes of pipes and FIFOs.

Get mode (--get)

Reports pipe buffer sizes as tab-separated columns: file descriptor name, buffer size in bytes, unread bytes (via FIONREAD ioctl). Defaults to stdin if no fd/file specified.

Set mode (--set)

Sets the buffer size for specified pipes/FIFOs. Defaults to stdout if no fd/file specified. Optionally executes a trailing command with the adjusted pipe sizes.

Inputs

SourcePurpose
Pipe/FIFO file descriptorsTarget for get/set operations
-f <path>FIFO path to operate on
/proc/sys/fs/pipe-max-sizeDefault size if --set given without value

Outputs

  • stdout (get mode): tab-separated table of fd name, buffer size, unread bytes

Syscalls

SyscallOperationDescription
fcntl(2)F_GETPIPE_SZGet pipe buffer size
fcntl(2)F_SETPIPE_SZSet pipe buffer size
ioctl(2)FIONREADGet unread byte count

Command-line options

OptionDescription
-g, --getReport pipe buffer sizes
-s, --set <size>Set pipe buffer size in bytes
-f, --file <path>Operate on a FIFO/pipe path (repeatable)
-n, --fd <N>Operate on file descriptor N (repeatable)
-i, --stdinShorthand for --fd 0
-o, --stdoutShorthand for --fd 1
-e, --stderrShorthand for --fd 2
-c, --checkExit immediately on any error
-q, --quietSuppress non-fatal warnings
-v, --verboseEmit headers (get) or print actual sizes (set)
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure

Notes

  • The kernel may round the requested size up to a page boundary.
  • The kernel refuses to shrink a buffer if it would cause data loss.
  • Unprivileged processes have limits on maximum pipe buffer size.
  • FIFO buffer size changes are not preserved across restarts.
  • Requires Linux 2.6.35+ for pipe buffer resizing.

Not yet implemented

  • Size suffix parsing (K, M, G, KiB, MiB, GiB)
  • Reading default from /proc/sys/fs/pipe-max-size when --set has no value

pivot_root

Change the root filesystem.

Synopsis

pivot_root new_root put_old

Operation

Calls the pivot_root(2) syscall to move the current root filesystem to put_old and make new_root the new root filesystem.

Typically used in boot scripts and container setup:

cd new_root
pivot_root . put_old
exec chroot . command

Inputs

  • new_root — path to the new root filesystem (must be a mount point)
  • put_old — path where the old root will be moved (must be under new_root)

Outputs

None. The syscall modifies the process’s mount namespace.

Syscalls

SyscallDescription
pivot_root(2)Move root filesystem

Command-line options

OptionDescription
new_rootNew root filesystem path
put_oldWhere to move the old root
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0Success
1Failure (syscall error)

Permissions

Requires CAP_SYS_ADMIN.

prlimit

Get and set process resource limits.

Reads limits using getrlimit(2) for the current process, or /proc/<pid>/limits for other processes. Sets limits using setrlimit(2) for self or prlimit(2) for other PIDs (requires CAP_SYS_RESOURCE).

Resource flags (--core, --nofile, etc.) accept an optional =limit value in soft:hard, soft:, :hard, or plain value format (use unlimited for no limit). Without =limit, the flag selects that resource for display only.

rfkill

Enable and disable wireless devices.

Reads device state from /sys/class/rfkill/ and sends block/unblock operations to /dev/rfkill using the kernel’s rfkill event interface.

Commands

CommandDescription
(none)List all devices in table format
list [id|type ...]List devices in legacy format
block <id|type> ...Soft-block one or more devices
unblock <id|type> ...Soft-unblock one or more devices
toggle <id|type> ...Toggle the soft-block state
eventStream rfkill events from /dev/rfkill

Identifiers can be numeric device IDs or type names: all, wlan/wifi, bluetooth, uwb/ultrawideband, wimax, wwan, gps, fm, nfc.

Output Columns

ColumnDescription
IDDevice identifier
TYPEDevice type name
DEVICEKernel device name
TYPE-DESCDevice type description
SOFTSoftware block status
HARDHardware block status

Default columns: ID, TYPE, DEVICE, SOFT, HARD.

Not Implemented

  • Hard-block reasons (rfkill_event_ext / RFKILL_IOCTL_MAX_SIZE) are not reported; only basic hard-block state (yes/no) is shown.

setpgid

Run a program in a new process group.

Implemented

  • Create a new process group and exec the given command
  • -f / --foreground: make the new process group the foreground group

setsid

Run a program in a new session.

Implemented

  • Create a new session and exec the given command
  • -c / --ctty: set the current terminal as the controlling terminal
  • -f / --fork: always fork (even if not process group leader)
  • -w / --wait: wait for the child and return its exit status
  • Automatic fork detection when already a process group leader

swapoff

Disable devices and files for paging and swapping.

Synopsis

swapoff device...
swapoff -a

Operation

Calls swapoff(2) to disable swapping on the specified device or file. The kernel moves all swap pages back to RAM before deactivating the area, which may take significant time if the swap is heavily used.

--all mode

Reads /proc/swaps to find all active swap areas and disables each one.

Inputs

SourcePurpose
Device/file pathTarget to disable
/proc/swapsEnumerate active swap areas for --all

Outputs

  • swapoff(2) syscall to disable swap

Syscalls

SyscallDescription
swapoff(2)Disable swapping on a device/file

Command-line options

OptionDescription
-a, --allDisable all active swap areas
-v, --verboseVerbose output
-h, --helpDisplay help
-V, --versionDisplay version

Exit codes

CodeMeaning
0All succeeded
4swapoff(2) failed
8Non-syscall system error
32All failed (--all mode)
64Some failed (--all mode)

Permissions

Requires CAP_SYS_ADMIN.

Notes

  • swapoff may take a long time if the swap area is heavily used, as all pages must be paged back into RAM.
  • If there isn’t enough free RAM to absorb the swap contents, swapoff will fail with ENOMEM.

Not yet implemented

  • -L, -U label/UUID specifiers (needs libblkid)

swapon

Enable devices and files for paging and swapping.

Synopsis

swapon [options] device...
swapon -a [options]
swapon --show[=columns]
swapon -s

Operation

Calls swapon(2) to enable swapping on the specified device or file.

Enable mode

Enables swap on one or more specified devices/files. Priority and discard policy can be configured via flags or fstab-style options.

--all mode

Reads /etc/fstab for entries with type swap, enables each one. Entries with the noauto option are skipped. Already-active swap areas are silently skipped.

--show mode (display only)

Reads /proc/swaps and displays a formatted table of active swap areas.

Inputs

SourcePurpose
Device/file pathTarget to enable as swap
/etc/fstabEnumerate swap entries for --all
/proc/swapsList active swap areas for --show/-s

Outputs

  • swapon(2) syscall to enable swap
  • stdout: swap area listing (--show, -s)

Syscalls

SyscallDescription
swapon(2)Enable swapping on a device/file

Flags for swapon(2)

FlagValueDescription
SWAP_FLAG_PREFER0x8000Priority is specified (OR’d with priority in lower 15 bits)
SWAP_FLAG_PRIO_MASK0x7fffPriority value mask (0-32767)
SWAP_FLAG_DISCARD0x10000Enable discard
SWAP_FLAG_DISCARD_ONCE0x20000Discard at swapon time
SWAP_FLAG_DISCARD_PAGES0x40000Discard freed page clusters

Command-line options

OptionDescription
-a, --allEnable all swap entries from /etc/fstab
-d, --discard[=policy]Enable discard (once, pages, or both)
-e, --ifexistsSilently skip non-existent devices
-p, --priority <N>Set swap priority (0-32767)
-s, --summaryDisplay /proc/swaps (deprecated)
--show[=columns]Display formatted table of swap areas
--noheadingsSuppress table headers
--bytesShow sizes in bytes
-v, --verboseVerbose output
-h, --helpDisplay help
-V, --versionDisplay version

--show columns

NAME, TYPE, SIZE, USED, PRIO

Exit codes

CodeMeaning
0Success
nonzeroFailure

Permissions

Requires CAP_SYS_ADMIN.

Not yet implemented

  • LABEL=, UUID=, PARTLABEL=, PARTUUID= device specifiers (needs libblkid)
  • -L, -U flags
  • -f, --fixpgsz (reinitialize swap on page size mismatch)
  • -o, --options (fstab-style option string)
  • -T, --fstab (alternative fstab)
  • --output-all, --raw output modes
  • Suspend data detection
  • Reading priority/discard from fstab options in --all mode

Terminal

Terminal-facing tools for sending messages to other users and controlling terminal access.

Implemented

  • mesg — display (or do not display) messages from other users
  • wall — write a message to all users
  • write — send a message to another user

Planned

agetty, script, scriptlive, scriptreplay, setterm.

mesg

Control whether other users can send messages to your terminal.

Implemented

  • Display current message permission (is y / is n)
  • y argument: allow messages (set group write on terminal)
  • n argument: disallow messages (clear group write on terminal)
  • -v / --verbose: explain what is being done
  • Exit code 0 for y, 1 for n

Text

Text-processing tools.

Implemented

  • colrm — remove columns from a file
  • column — columnate lists
  • hexdump — display file contents in hexadecimal, decimal, octal, or ascii
  • line — read one line
  • rev — reverse lines characterwise

Planned

bits, col, colcrt, more, pg, ul.

colrm

Remove columns from lines of text.

Implemented

  • Remove columns by range: colrm [first [last]]
  • Tab expansion (8-column tab stops)
  • Backspace handling
  • Partial tab removal at column boundaries

hexdump

Display file contents in hexadecimal, decimal, octal, or ASCII.

Implemented

  • -C / --canonical: hex+ASCII display (also available as hd)
  • -b / --one-byte-octal: one-byte octal display
  • -X / --one-byte-hex: one-byte hex display
  • -c / --one-byte-char: one-byte character display
  • -x / --two-bytes-hex: two-byte hex display
  • -d / --two-bytes-decimal: two-byte decimal display
  • -o / --two-bytes-octal: two-byte octal display
  • Default format (two-byte hex, compact spacing)
  • -n / --length: limit bytes read
  • -s / --skip: skip bytes from start
  • -v / --no-squeezing: show all data (no * for identical lines)
  • Read from files or stdin
  • Line squeezing (identical consecutive lines replaced with *)

Not yet implemented

  • -e / --format: custom format strings
  • -f / --format-file: format strings from file
  • -L / --color: colorized output
  • Trailing space padding on short final lines
  • hd multicall alias

line

Read one line from standard input.

Implemented

  • Read a single line from stdin, write to stdout
  • Exit code 0 on success, 1 on EOF

rev

Reverse lines characterwise.

Implemented

  • Character-level reversal (Unicode-aware)
  • Read from files or stdin
  • -0 / --zero: use NUL as line delimiter instead of newline