Recent from talks
All channels
Be the first to start a discussion here.
Be the first to start a discussion here.
Be the first to start a discussion here.
Be the first to start a discussion here.
Welcome to the community hub built to collect knowledge and have discussions related to List of POSIX commands.
Nothing was collected or created yet.
List of POSIX commands
View on Wikipediafrom Wikipedia
Not found
List of POSIX commands
View on Grokipediafrom Grokipedia
The list of POSIX commands comprises the standardized set of command-line utilities and shell commands defined in the POSIX.1 standard, a family of IEEE specifications designed to ensure compatibility and portability of applications across Unix-like operating systems. These commands, detailed in the Shell and Utilities volume, include essential tools for file and directory management (such as
cat, chmod, and ls), process control (like ps and kill), text processing (including awk, grep, and sed), and shell builtins (e.g., cd, echo, and test), providing a core interface for scripting and system administration in conformant environments.[1]
Developed through collaboration between the IEEE and The Open Group, POSIX.1 originated in the 1980s to unify divergent Unix variants, with the first standard (IEEE Std 1003.1-1988) establishing foundational utilities drawn from historical systems like UNIX. Subsequent revisions, such as POSIX.1-2017 and the latest POSIX.1-2024 (IEEE Std 1003.1-2024), have refined and expanded the utilities to incorporate modern requirements, including support for internationalization, asynchronous I/O, and C language compilation via tools like c99 or c17, while maintaining backward compatibility for portable software development.[2] The utilities are categorized into mandatory ones required on all POSIX-conformant systems and optional extensions for specific features, such as user portability or realtime extensions, enabling developers to write code that runs reliably without platform-specific adaptations. This standardization has profoundly influenced operating systems like Linux, macOS, and BSD derivatives, fostering a vast ecosystem of open-source tools and ensuring interoperability in enterprise and embedded computing.
Introduction to POSIX
Definition and Purpose
POSIX, an acronym for Portable Operating System Interface, is a family of standards specified by the IEEE Computer Society to maintain compatibility across operating systems, with a focus on Unix-like environments. IEEE Std 1003.1, commonly referred to as POSIX.1, establishes a standardized operating system interface and environment that includes a command interpreter—known as a shell—and a set of common utility programs. This standard supports applications portability at the source code level by defining consistent interfaces for system services, shell operations, and utilities.[3][4] The primary purpose of POSIX commands lies in ensuring that a core collection of command-line utilities operates uniformly across POSIX-compliant systems, thereby enhancing software portability and interoperability. These commands form the Shell and Utilities component of POSIX.1, which provides a source code-level interface for command interpretation and essential tools, allowing developers to create applications that function reliably without extensive modifications when moving between platforms. By standardizing these utilities, POSIX addresses the fragmentation in Unix-like operating systems, promoting the development of reusable code and reducing the complexity of cross-system deployment.[5] At its core, POSIX commands must conform to strict principles regarding syntax, options, and behaviors, as detailed in IEEE Std 1003.1. Utilities follow a defined argument syntax where options are denoted by a leading hyphen followed by alphanumeric characters, operands appear after options, and specific conventions govern option-argument handling to ensure predictable parsing and execution. These rules, including the use of double hyphens to terminate option processing, guarantee consistent invocation and output across implementations, minimizing ambiguities in command usage.[6][3] The benefits of this standardization are evident in reduced vendor lock-in, as organizations can avoid dependency on proprietary extensions, and in simplified migration of scripts and applications between diverse systems such as Linux distributions, BSD variants, and Solaris. For example, POSIX compliance enables shell scripts written for one Unix-like environment to execute with minimal adaptation on another, streamlining development workflows and lowering maintenance costs in multi-platform deployments.[5][7]Historical Development
The development of POSIX standards began in the mid-1980s amid fragmentation in Unix-like operating systems, as vendors sought to create compatible systems without infringing on AT&T's "Unix" trademark, which restricted direct use of the name and proprietary interfaces. In 1985, the IEEE formed the Portable Operating System Interface for Computer Environments (POSIX) working group, sponsored by the IEEE Standards Board, to define portable interfaces for application portability across diverse systems.[8][5] The inaugural POSIX standard, IEEE Std 1003.1-1988 (also known as POSIX.1), was ratified in 1988 and focused on core system interfaces such as system calls and headers for basic operations like file management and process control. The shell and utilities were subsequently standardized in IEEE Std 1003.2-1992 (POSIX.2). Subsequent revisions addressed gaps and amendments; IEEE Std 1003.1-1990 incorporated early corrections to POSIX.1. Major updates continued with IEEE Std 1003.1-2001, which unified prior parts into a cohesive base specification, and IEEE Std 1003.1-2008, which integrated real-time extensions from earlier supplements like POSIX.1b. The 2016 edition of IEEE Std 1003.1-2008 incorporated technical corrigenda addressing issues identified since 2008. Most recently, IEEE Std 1003.1-2024 introduced support for modern features, including UTF-8 character encoding in locales and utilities.[9][10][3] In the 1990s, The Open Group adopted and maintained POSIX as the foundation for the Single UNIX Specification (SUS), starting with Version 1 in 1995 as a superset to ensure certification for Unix-branded systems. This collaboration between IEEE and The Open Group has sustained POSIX's evolution, with SUS versions aligning closely with IEEE updates. Over time, the standards' scope for commands expanded gradually, from approximately 118 core utilities in the 1992 POSIX.2 version to over 200 in the 2024 edition, reflecting additions for enhanced portability and functionality in diverse environments.[11][2]POSIX Standards for Commands
IEEE 1003.1 Evolution
The IEEE Std 1003.1, commonly known as POSIX.1, establishes a standard operating system interface and environment to promote software portability across compliant systems. Its scope encompasses system interfaces such as process management, file operations, and signals, with Section 2 dedicated to the Shell and Utilities, which defines the syntax, options, behaviors, and expected outputs for command-line utilities essential for application development and scripting.[3] The standard's evolution began with IEEE Std 1003.1-1988, which primarily specified core system calls and headers for basic portability but excluded shell and utilities, deferring those to the separate IEEE Std 1003.2-1992 for command language and utility programs. A pivotal shift occurred in IEEE Std 1003.1-2001, which merged the shell and utilities into POSIX.1, aligning with the Single UNIX Specification version 3 and mandating a core set of utilities; this revision also introduced 64-bit support through large file interfaces (e.g., extensions for off_t types) and internationalization via locale-aware behaviors in utilities, such as UTF-8 handling in text processing commands.[12] Subsequent updates built on this foundation. IEEE Std 1003.1-2008 integrated real-time extensions from POSIX.1b (e.g., priority scheduling and timers) and threads from POSIX.1c, enhancing utilities like ps for process reporting and kill for signal delivery in multithreaded environments. The 2017 revision (IEEE Std 1003.1-2017) refined utility specifications for improved security and consistency, including deprecation of non-portable historical behaviors in utilities and better alignment with secure coding practices, such as safer default permissions in file utilities.[13] The most recent edition, IEEE Std 1003.1-2024, addresses contemporary needs with updates for modern hardware, including further large-scale system support and resolved integration issues from prior amendments.[3][14] Command-specific evolutions emphasize standardization of options and behaviors to minimize portability issues. For instance, later versions clarified mandatory versus optional options across utilities (e.g., -l for ls and -f for ps), deprecated vendor-specific extensions like non-standard flags in grep, and promoted consistent error handling to reduce implementation variances. These changes ensure utilities behave predictably, such as standardized output formats in text processing tools like awk and sed.[6] POSIX.1 defines compliance levels to accommodate varying implementation scopes: full conformance requires all mandatory system interfaces and utilities, while partial conformance allows subsets with documented deviations, particularly for optional features in commands. Utilities form a critical test area, as their correct implementation directly impacts shell scripting and application interoperability.[15] Verification of command implementations relies on standardized testing, notably the VSX-PCTS (Verification Suite for POSIX Conformance Test Suite), an official suite from The Open Group that exercises shell and utilities for adherence to specified interfaces, options, and behaviors across versions. This testing ensures robust portability, with suites updated to match revisions like 1003.1-2017 and 1003.1-2024.[16][17]Open Group Base Specifications
The Open Group has maintained and extended POSIX command specifications since 1997, when POSIX.1 was integrated into Version 2 of the Single UNIX Specification (SUS), building on the IEEE Std 1003.1-1996 standard to provide a unified framework for portable Unix-like systems. This integration marked a shift toward practical, industry-wide adoption, with subsequent SUS versions evolving in collaboration with the Austin Group—a joint effort involving IEEE, The Open Group, and other stakeholders—to ensure compatibility across diverse operating environments. The current iteration, SUS Issue 8 (published in 2024 and aligned with POSIX.1-2024), continues this tradition by harmonizing core POSIX requirements with real-world extensions for enhanced portability.[18] The Open Group Base Specifications, available at pubs.opengroup.org, offer detailed documentation on POSIX commands, including precise syntax, required environment variables, invocation options, and standardized exit statuses to facilitate consistent behavior across compliant systems.[19] These specifications extend beyond the foundational IEEE POSIX.1 standard by incorporating X/Open System Interfaces (XSI) extensions, such as historical Unix utilities likelp for printing and od for octal dumping, which augment the core POSIX command set without altering its fundamental portability guarantees. This approach ensures that SUS-compliant systems support a broader ecosystem of tools while preserving the minimal, verifiable interface defined by POSIX.
Certification under The Open Group's program, including legacy brands like UNIX 98 and UNIX 03, mandates full compliance with SUS command specifications, with vendors required to pass rigorous testing via the organization's conformance suites that validate utility behavior, error handling, and interface consistency. These tests cover over 1,000 utilities and interfaces, ensuring that certified systems deliver predictable outcomes in multi-vendor environments. Recent updates in SUS Issue 8 introduce modern enhancements, such as new utilities including gettext, msgfmt, ngettext, readlink, realpath, timeout, and xgettext for internationalization and process management, alongside networking improvements like the accept4() function and socket options such as SO_DOMAIN and SO_PROTOCOL.[20][21] These additions address contemporary needs for secure, efficient operations while maintaining backward compatibility with prior issues.
Categorized POSIX Commands
File and Directory Operations
File and directory operations form a core component of POSIX utilities, allowing portable management of the file system structure across compliant operating systems. These commands facilitate navigation between directories, creation and removal of files and directories, copying and moving resources, and linking files, all while adhering to standardized behaviors defined in IEEE Std 1003.1-2024. They are essential for scripting and everyday user interactions, ensuring consistency in file hierarchy manipulation without reliance on implementation-specific extensions.[19] Thecd command changes the current working directory of the shell. Its syntax is cd [-L|-P] [directory] or cd - to return to the previous directory. If no directory is specified, it defaults to the value of the HOME environment variable. The -L option (default) performs logical handling of path components like dot-dot without resolving symbolic links, while -P uses physical resolution. This utility is always implemented as a shell built-in and requires execute permission on the target directory.[22]
To create directories, the mkdir command is used, with syntax mkdir [-p] [-m mode] dir.... It establishes new directories at the specified pathnames, applying a default mode of rwxrwxrwx masked by the current umask unless overridden by -m. The -p option creates any necessary parent directories without error if they already exist. Intermediate directories created with -p receive rwxrwx--- permissions initially.[23]
For removing empty directories, [rmdir](/page/Rmdir) employs the syntax rmdir [-p] dir.... It deletes the specified directory entries only if they contain no files other than . and ... The -p option recursively removes parent directories in the pathname if they become empty after deletion. Directories must be processed from innermost to outermost to avoid errors due to non-emptiness.[24]
The mv command moves or renames files and directories, using syntax mv [-if] source_file target_file for single items or mv [-if] source_file... target_dir for multiple sources into a directory. On the same filesystem, it uses the rename() function for efficiency; across filesystems, it copies and removes the source. The -i option prompts before overwriting existing targets, while -f suppresses prompts and errors for non-existent sources. Directory moves require the source to be empty if the target exists.[25]
Copying is handled by cp, with syntax cp [-fip] source_file target_file, cp [-fip] source_file... target, or cp -r [-H|-L|-P] [-fip] source_file... target for recursive hierarchies (note: POSIX uses -r lowercase, equivalent to -R). It duplicates files or entire directory trees, preserving characteristics where possible. The -p option maintains timestamps, ownership, and modes; -i prompts overwrites; -f forces unlinking of destinations on failure. For hierarchies, -H follows command-line symbolic links, -L follows all, and -P treats them as files. Special files like devices have implementation-defined behavior.[26]
File and directory removal is performed by rm, syntax rm [-i] [-r|-R] file... or rm -f [options] file.... It unlinks files or recursively removes hierarchies with -r or -R. The -i option prompts for confirmation on writes to terminals, and -f inhibits prompts and non-existent file diagnostics. Directories require -r for deletion, and the command skips . and ... It does not follow symbolic links but removes them if specified. Attempting to remove running executables may fail with EBUSY.[27]
The touch utility updates file timestamps or creates empty files, using syntax touch [-acm] [-r ref_file | -t time | -d date_time] file.... Without time options, it sets both access and modification times to the current time. The -a flag affects only access time, -m only modification time, and -c prevents creation of non-existent files. Time can be specified via -r (reference file), -t (format [[CC]YY]MMDDhhmm[.SS]), or -d (ISO 8601 format). Created files use default modes masked by umask, and timestamps support at least up to 2038 UTC.[28]
Linking files is achieved with ln, syntax ln [-fs] [-L|-P] source_file target_file or ln [-fs] [-L|-P] source_file... target_dir. By default, it creates hard links; -s produces symbolic links. The -f option removes existing targets; -L dereferences symbolic links for linking; -P links to the symlink itself. Directory linking is implementation-defined without -s. Hard links require same-device sources, while symbolic links do not.[29]
To display the current working directory, pwd outputs an absolute pathname with syntax pwd [-L|-P]. The -L option (default) uses the PWD environment variable if valid; -P resolves all symbolic links for a physical path. It prints to standard output without trailing slashes except for root. Paths exceeding PATH_MAX with -L yield unspecified results.[30]
Directory contents are listed by ls, syntax ls [-A|-a] [-C|-m|-x|-1] [-F|-p] [-H|-L] [-R|-d] [-S|-f|-t] [-c|-u] [-ikqrs] [-glno] [file...]. It displays names and details for files or directories (recursing with -R). The -l option provides long format with permissions, sizes, and timestamps; -a includes hidden files; -i shows inode numbers. Sorting defaults to lexicographic; -t by time, -S by size. Non-printable characters are quoted with -q. Options like --color for colored output are common extensions but not part of the POSIX standard. Infinite directory loops trigger diagnostics. In POSIX.1-2024, enhanced handling for file names containing newlines improves portability.[31]
These commands support portable scripting for file system tasks, such as automating backups with cp -r or cleanup with rm -r, while -i options enhance safety in interactive use. POSIX mandates specific options for interoperability, though implementations may add extensions like recursive -p in mv for directories, which are not required.[19]
Text Processing and Manipulation
Text processing and manipulation in POSIX environments involve utilities designed to read, search, transform, and output text data from files or standard input streams, enabling efficient data pipelines for tasks such as log analysis and report generation. These commands emphasize stream-oriented processing, where output from one utility serves as input to another via pipes (|), facilitating modular workflows without intermediate file storage. All specified commands conform to the POSIX.1-2024 standard (IEEE Std 1003.1-2024), ensuring portability across compliant systems, and they return exit codes to indicate success (0) or errors (>0), with grep additionally using 1 for no matches found.[19] Thecat command concatenates and displays the contents of files or standard input to standard output, serving as a foundational tool for combining text streams. It supports no specific options in the basic POSIX specification but handles multiple input files sequentially. For instance, cat file1.txt file2.txt merges the files for further processing, such as piping to a search utility, and is commonly used to prepare input for extraction tasks after file creation via other utilities.
Searching within text is handled by grep, which selects lines matching a basic regular expression (BRE) pattern, with the -i option enabling case-insensitive matching. It reads from standard input or files and outputs matching lines to standard output, making it ideal for filtering logs in pipelines like cat access.log | grep -i "error". POSIX BRE support includes anchors (^, $) and quantifiers (*, .), but not extended features like + without escaping.
Transformations are performed by sed, a stream editor that applies editing commands to input lines, such as substitutions via the syntax s/old/new/g for global replacement using BRE. It processes standard input non-interactively and writes to standard output, with examples including sed 's/error/warning/g' input.txt to normalize text before field extraction. Like grep, sed's regex is basic POSIX, requiring backslashes for extended operators. Exit codes reflect successful processing or syntax errors in scripts.
For pattern scanning and field-based processing, [awk](/page/AWK) provides a scripting language that scans input for patterns and performs actions, such as {print $1} to output the first whitespace-delimited field. It supports extended regular expressions (ERE) and treats input as records with fields ($1, $2, etc.), reading from standard input and writing to standard output. A typical pipeline might be awk '/error/ {print $2}' log.txt | sort, useful for generating reports from structured data like CSV files. POSIX awk includes basic arithmetic but focuses here on text manipulation.
Sorting and deduplication are managed by sort and uniq. The sort utility orders lines lexicographically or numerically (-n option for numeric comparison), reading from standard input and outputting to standard output, as in sort -n numbers.txt for ordered data extraction. It handles large streams efficiently for report preparation. Following sort, uniq discards adjacent duplicate lines, requiring sorted input via pipe like sort file.txt | uniq, and reports unique entries for streamlined output in analysis pipelines.
Field extraction is facilitated by cut, which removes sections from lines using a delimiter (-d option, e.g., -d',' for comma-separated values) and selects fields (e.g., -f1 for the first), outputting to standard output from standard input. An example is cut -d' ' -f1,3 data.txt | grep "key", isolating columns for targeted searching. Conversely, paste merges corresponding lines from multiple files or standard input, producing tab-separated output by default, as in paste list1.txt list2.txt to combine datasets for comparison in reports. The -d option customizes delimiters (e.g., -d '\t\n' for tab-separated then newline), cycling through a list for multi-file inputs, while -s serializes each file's lines into one output line. It processes until all inputs reach EOF, padding shorter files with empty fields if needed, and exits with 0 on success or non-zero for I/O errors.[32]
Character-level operations are covered by tr, which translates, squeezes, or deletes characters, such as converting uppercase to lowercase with tr '[A-Z]' '[a-z]'. It operates on standard input to standard output, often in pipelines like cat file.txt | tr ' ' '\n' | sort to normalize and process text streams for generation tasks. Finally, head and tail extract the beginning (head -n 10 file.txt) or end (tail -n 5 log.txt) of inputs, limiting output lines for previews or recent data analysis, with both supporting standard input for piped workflows.
Process Control and Management
Process control and management in POSIX encompass utilities that enable users and scripts to initiate, monitor, adjust priorities, and terminate processes, ensuring portability across compliant systems. These commands are essential for resource allocation, signal handling, and job orchestration in multi-process environments, as defined in the IEEE Std 1003.1-2024 standard.[2] They support PID (process identifier) management, where each process is uniquely identified by a non-negative integer, facilitating precise control without interfering with system-wide operations. Theps command reports the status of active processes, providing details such as PID, terminal association, CPU time, and command name. In POSIX, invoking ps with the -e option displays information for all processes, excluding those whose output would be identical to the invoking process, which aids in comprehensive monitoring for scripting and debugging. For example, ps -e outputs a list of all running processes in a tabular format, helping administrators identify resource-intensive tasks.
To terminate processes, the kill utility sends signals to specified processes or process groups, identified by PID or job control notations. POSIX requires kill to support standard signals like SIGTERM (default for graceful termination) and SIGKILL (-9 option for forceful termination), with kill -l listing all supported signal names and numbers for portability. Signal handling in POSIX ensures that processes can respond to interrupts, such as SIGHUP for hangup events, promoting reliable automation in shell scripts.
Priority adjustment is handled by the nice command, which executes a utility with a modified scheduling priority. The syntax nice -n adjustment command sets the niceness value (range -20 to 19, where lower values indicate higher priority), allowing users to influence CPU scheduling without root privileges for positive adjustments. This is particularly useful in resource control scenarios, such as running non-urgent batch jobs with nice -n 10 long_running_script to yield to interactive tasks.
For background execution resilient to session termination, nohup runs a command immune to SIGHUP signals, redirecting output to nohup.out by default. POSIX specifies that nohup command continues execution even if the controlling terminal closes, supporting unattended script automation on remote or logout-prone sessions.
POSIX job control, mandated by IEEE Std 1003.1, enables interactive management of asynchronous processes within shells, including stopped and background jobs. The jobs command lists active jobs with their PIDs, status (running, stopped), and job numbers, as in jobs -l for detailed PID output, facilitating oversight in multi-task environments. Commands like bg resume suspended jobs in the background (bg %jobnumber), while fg brings them to the foreground for input interaction. The wait utility suspends execution until child processes complete, returning their exit status via wait PID, which is crucial for sequential scripting and error handling in automation workflows.
These utilities integrate with shell built-ins for seamless job control, enhancing script reliability in POSIX-compliant environments. Common use cases include automating resource-intensive tasks, such as batch processing with adjusted priorities, and managing long-running jobs in distributed systems to optimize performance and prevent hangs.[2]
Arithmetic and Data Processing
The POSIX standard includes several utilities for performing arithmetic calculations and processing structured data, enabling basic numerical operations and file merging directly within shell environments. These commands facilitate computations and data integration without requiring full-fledged programming languages, making them essential for scripting tasks involving integer arithmetic, decimal handling, and field-based joins. Key utilities in this category emphasize portability and simplicity, supporting integer-based expressions and delimited file operations. Thebc utility serves as an arbitrary-precision calculator, processing mathematical expressions from input files or standard input, with interactive support when invoked from a terminal.[33] It handles unlimited precision integers and decimals controlled by the scale variable, which defaults to 0 for integer-only results but can be set higher (up to {BC_SCALE_MAX}) for fractional outputs, such as in scale=2; 1/3 yielding 0.33.[33] The -l option loads a math library providing functions like sqrt(x) for square roots and trigonometric operations (e.g., s(x) for sine in radians), setting scale to 20 by default.[33] In non-interactive mode, bc processes statements sequentially and exits with status 0 on success or non-zero on errors like syntax issues. This makes bc suitable for shell scripts requiring precise decimal computations, such as financial calculations, where it avoids floating-point inaccuracies inherent in other tools.[33]
In contrast, the expr utility evaluates simple integer arithmetic and string expressions provided as command-line operands, outputting the result to standard output.[34] It supports operations like addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) on decimal integers, but lacks floating-point support, limiting it to whole-number results; for example, expr 5 + 3 returns 8.[34] Operators must be escaped in shell contexts (e.g., expr 2 \* 3), and nesting is constrained by {EXPR_NEST_MAX} to prevent excessive complexity.[34] Exit status is 0 if the result is non-zero/non-null, 1 if zero/null, and greater than 1 for errors like invalid syntax, allowing scripts to handle failures gracefully.[34] Commonly used in shell scripts for conditional arithmetic, such as incrementing counters (n=$(expr $n + 1)), expr provides lightweight evaluation without the overhead of a full calculator.[34]
For data processing, the join utility performs relational-style equality joins on two sorted files, comparing specified fields (default first) and outputting combined lines for matches.[35] Fields are delimited by spaces (or a custom -t character), and inputs must be sorted via sort -b for compatibility; options like -1 and -2 select join fields, -o controls output (e.g., 1.1 2.2 for specific columns), and -a or -v include or isolate unmatched lines.[35] Empty output fields can be filled with -e, and the utility exits with 0 on success or non-zero for errors like unsorted input. In shell workflows, join enables data correlation, such as merging user and transaction files on IDs, supporting tabular processing without database tools. For merging lines from multiple files, see the paste utility under text processing.[35]
These utilities collectively address arithmetic and data merging needs in POSIX-compliant systems, promoting script-based automation for computations and integrations while handling integers robustly and deferring advanced floating-point work to higher-level environments.[33][34][35]
System Information and Administration
The POSIX commands for system information and administration enable users and administrators to query resource usage, system characteristics, and user activity, facilitating monitoring and maintenance tasks in conforming environments. These utilities provide essential data on disk space, hardware and software details, login sessions, time settings, and identity information, often integrated into scripts for automated diagnostics. While most operate without special privileges for querying, certain operations like setting the system date require root access to prevent unauthorized modifications.[36] Thedf command reports free disk space on file systems accessible to the invoking user, displaying total space, used space, available space, and percentage utilization. By default, it uses 512-byte blocks, but the -k option specifies 1024-byte units for more readable output in kilobytes; the -P option ensures a portable format with headers like "Filesystem 1024-blocks Used Available Capacity Mounted on". For example, df -k might output lines such as /dev/sda1 1048576 524288 524288 50% /, rounded up to the next block. Non-POSIX extensions like -h for human-readable sizes (e.g., GB) are common but not required for conformance. This utility aids in identifying storage constraints during routine system checks.[37]
Similarly, du estimates the space allocated to files and directories within a specified hierarchy, defaulting to 512-byte units and following symbolic links only for their size, not the referenced files. The -s option provides a summary total for each operand, such as du -s /home yielding 102400 /home to indicate 50 MB usage. Other options include -a to list individual files and -k for kilobyte units, with -x restricting output to the same device to avoid crossing file system boundaries. Administrators use du in scripts to track directory growth and optimize storage.[38]
The [uname](/page/Uname) command outputs basic system information, printing the operating system name by default but providing more details with options. Invoking uname -a displays all fields in the format "sysname nodename release version machine", for instance, "Linux hostname 5.4.0-1-generic #2-Ubuntu SMP x86_64", where -m specifies machine hardware, -r the release, and -v the version. These details, derived from the POSIX uname() function, help verify system compatibility in deployment scripts. The command's behavior can be influenced by environment variables like PATH, which determines its location in the file system search.[39]
For user activity, who lists currently logged-in users, showing login name, terminal line, and login time in a default format like "user pts/0 Nov 9 10:30". The -m option limits output to the invoking user's processes, while -T adds terminal state indicators (+ for write-allowed, - for denied). On XSI-conformant systems, it may include idle time or process ID, but POSIX requires only core fields. This is valuable for monitoring concurrent access in multi-user environments.[40]
The date command displays or sets the system date and time, outputting in the default POSIX locale format "%a %b %e %H:%M:%S %Z %Y", such as "Sun Nov 9 14:22:01 UTC 2025". The -u option uses UTC, and a +format string allows customization, e.g., date +%Y-%m-%d for "2025-11-09". Setting the date via operands like date 110914222025 (month day hour minute year) requires appropriate privileges, typically root, to update the system clock. It supports administrative tasks like synchronizing timestamps in logs.[36]
Although not a standard POSIX utility, the uptime command is commonly available on Unix-like systems to report system runtime since the last boot, current time, and logged-in user count, e.g., "14:22:01 up 2 days, 3:45, 5 users, load average: 0.10, 0.20, 0.30". It derives from implementation-specific facilities and integrates with process statistics for overall health monitoring.
The id command prints user and group identity information for the current process or a specified user. Without arguments, it outputs "uid=1000(user) gid=1000(user) groups=1000(user),4(adm),24(cdrom)", showing real and effective IDs with names if available via the password database. Options like -u for effective user ID (1000), -g for group ID, or -G for all group IDs enable targeted queries; -n substitutes names for numbers. This supports identity verification in access control scripts, assuming real equals effective IDs for other users.[41]
These commands collectively support system-wide diagnostics, with behaviors influenced by environment variables such as PATH for command resolution and TZ for time zones in date. They are often combined in shell scripts for proactive administration, like alerting on low disk space via df thresholds.
User Environment and Shell Built-ins
The POSIX shell, provided by thesh utility, includes a set of built-in commands that manage the user environment, variables, and interactive sessions without invoking external processes, thereby avoiding the overhead of forking and executing separate binaries.[42] These built-ins are integral to the shell's execution environment, which maintains variables, aliases, and the current working directory for the duration of the shell process or its subshells.[43] Unlike external commands, built-ins like cd operate directly within the shell, updating the environment immediately without creating child processes.[22] The POSIX standard requires the sh utility to support these built-ins as part of its command language interpreter, ensuring portability for scripting and interactive use across conforming systems.[42]
Variable management in the POSIX shell relies on expansion rules that allow dynamic substitution during command processing. For instance, $VAR expands to the value of the variable VAR, with optional braces ${VAR} for clarity or to disambiguate boundaries, such as in ${VAR}suffix.[44] Expansions occur in a defined order—after tilde and command substitution but before field splitting and pathname expansion—enabling variables to influence command arguments and redirections.[43] The shell requires variables to be set via assignment (e.g., VAR=value) before expansion, with special parameters like $? (exit status) and $$ (process ID) providing runtime information.[45] These rules support basic scripting by allowing environment customization, such as setting paths or flags interactively.
The export built-in marks variables for inclusion in the environment of child processes, ensuring they are inherited by subsequent commands.[46] Its synopsis is export name[=word]... or export -p, where -p lists all exported variables in a format suitable for reinput (e.g., export VAR=value).[46] It exits with status 0 on success and cannot export read-only variables.[46] Conversely, unset removes variables or functions from the environment, using unset [-fv] name... to target variables (-v) or functions (-f), with no error for non-existent names.[47] Read-only variables cannot be unset, and the command returns 0 only if all operations succeed.[47] The readonly built-in declares variables as immutable, via readonly name[=word]... or readonly -p for listing, preventing subsequent assignments or unsets.[48] These commands enable secure environment configuration in scripts, such as protecting critical paths from accidental modification.[48]
For directory navigation, the built-in cd changes the shell's working directory without forking, as detailed in the file operations section, updating the PWD and OLDPWD variables accordingly. It returns 0 on success or greater than 0 on failure, leaving the directory unchanged in the latter case.[22] This built-in is essential for interactive sessions, allowing seamless movement between directories in scripts or prompts.
Output and conditional testing are handled by echo and test/[, respectively. The echo built-in prints arguments to standard output followed by a newline, as in echo [string...], with no options in base POSIX but support for -n to suppress the newline in XSI extensions.[49] It returns 0 on success, making it a staple for debugging scripts by displaying variable expansions (e.g., echo $PATH).[49] The test built-in (synonymous with [ expression ], requiring a closing ] operand) evaluates file, string, or integer conditions, exiting 0 for true, 1 for false, and greater than 1 on errors.[50] Common primaries include -f file (exists and is a regular file) or string1 = string2; it supports unary and binary operators but recommends avoiding obsolescent logicals like -a for portability.[50] These facilitate conditional scripting, such as if [ -d dir ]; then cd dir; fi.
Alias management customizes the interactive shell via alias and unalias. The alias built-in defines shortcuts with alias [name[=string]...] or lists all aliases without arguments, affecting only the current shell and subshells (e.g., alias ll='ls -l').[51] It returns 0 on success. The unalias built-in removes them using unalias name... or unalias -a for all, returning 0 if successful.[52] Aliases expand during command search before functions or utilities, aiding user productivity in interactive environments but requiring careful quoting to avoid recursion.[53] Together, these built-ins support shell customization for repeated tasks, such as abbreviating common commands in profiles.[51]
Development and Programming Utilities
The development and programming utilities in POSIX provide essential tools for software construction, including build automation, library management, compilation, and parser generation, enabling developers to create portable applications across conforming systems. These utilities are specified in the IEEE Std 1003.1 standard, particularly under the Software Development Utilities option, which ensures consistent behavior for tasks like compiling C code and generating lexical analyzers.[54] They integrate with other POSIX components, such as the C library and shell, to support the full software lifecycle from source code to executable binaries.[55] Themake utility automates the building of programs by managing dependencies and executing commands to update target files based on changes in source files or prerequisites. It reads a makefile containing rules that define targets (files to build), dependencies (prerequisites that must be current), and shell commands for construction; for instance, if a source file is newer than its object file, make rebuilds the latter.[54] Key options include -f to specify a makefile, -n for a dry run without execution, and -j for parallel jobs (though parallelism is implementation-defined). In POSIX.1-2024, the default compiler invocation for C rules is now c17, aligning with ISO/IEC 9899:2018 support. Standards for portable makefiles require starting with the .POSIX target to enforce strict compliance, avoiding non-standard features like pattern rules, and using built-in macros such as $@ (target name) and $< (first prerequisite) for cross-platform compatibility.[54] In use cases like building multi-threaded applications, make supports integration with POSIX threads by incorporating compiler flags (e.g., -pthread) in rules, ensuring thread-safe compilation and linking.[54]
The ar utility creates and maintains archive libraries by grouping object files into a single file, facilitating static linking in software development. It supports operations such as adding (-r), deleting (-d), extracting (-x), and moving files within the archive, with a required symbol table (-s) for linker use when containing relocatable object files.[56] The -t option prints a table of contents listing archive members in order, optionally with verbose details like file sizes and timestamps via -v, aiding developers in inspecting library contents without extraction.[56] Archives are portable across POSIX systems, with filenames limited to the last component of paths, and this utility is crucial for packaging reusable code modules in maintainable software projects.[56]
While the linker ld is not a directly specified POSIX command—typically invoked indirectly by compilers—it plays a vital role in resolving symbols and producing executables from object files and libraries during the build process. In POSIX environments, linking adheres to the C standard's requirements for relocatable objects and shared libraries, ensuring portability when combined with tools like ar and c17.[55]
The c17 utility invokes the standard C compiler to process ISO C conforming source code, integrating preprocessing, compilation, assembly, and linking into executables or object files. It accepts operands like source files (.c), objects (.o), or archives (.a), with options such as -c for compilation only, -o for output naming, -I for header directories, -L for library paths, and -l to link specific libraries.[55] This ensures portable invocation across systems supporting programming environments like _POSIX_V7_LP64_OFF64, promoting consistent C program development as defined in ISO/IEC 9899:2018.[55] Developers use c17 for building and maintaining software packages, verifying compliance with the C17 standard during compilation.[55]
The lex and yacc utilities generate components for lexical analysis and parsing, essential for compiler and interpreter development. lex processes input files describing regular expressions and actions, producing C code (e.g., lex.yy.c) for a lexical analyzer function yylex() that tokenizes input streams.[57] Input follows a format with definitions (e.g., %{%} for C code), rules (patterns like DIGIT [0-9]+ followed by actions), and subroutines, separated by %%; output links with -ll for runtime support.[57] yacc complements this by accepting grammar specifications in a declarative language—divided into declarations (tokens via %token, precedence with %left), rules (e.g., expr : expr '+' term), and C code—generating yyparse() for syntax analysis.[58] Together, lex and yacc integrate seamlessly, with yylex() feeding tokens to yacc's parser, enabling portable construction of language processors in software projects.[57][58]