Recent from talks
Nothing was collected or created yet.
Yes (Unix)
View on Wikipedia| yes | |
|---|---|
Example usage of yes command which prints "Wikipedia" continuously until killed | |
| Operating system | Unix and Unix-like |
| Platform | Cross-platform |
| Type | Command |
| License | coreutils: GPLv3+ |
yes is a command on Unix and Unix-like operating systems, which outputs an affirmative response, or a user-defined string of text continuously until killed by the user.
Overview
[edit]By itself, the yes command outputs 'y' or whatever is specified as an argument, followed by a newline repeatedly until stopped by the user or otherwise killed; when piped into a command, it will continue until the pipe breaks (i.e., the program completes its execution). However, if the user enters a string after 'yes,' yes will output the string the same as it would 'y,' similar to echo.
The version of yes bundled in GNU coreutils was written by David MacKenzie.[1]
The command is available as a separate package for Microsoft Windows as part of the GnuWin32 project[2] and the UnxUtils collection of native Win32 ports of common GNU Unix-like utilities.[3]
Uses
[edit]yes can be used to send an affirmative (or negative; e.g. yes n) response to any command that would otherwise request one, thereby causing the command to run non-interactively.
Piping yes to a command with many user-confirmation prompts will automatically answer all of those prompts with "yes" (typing 'y' and pressing return).
The following commands
$ yes | sudo apt install foobar
will answer the prompts for confirmation with y, effectively installing foobar with sudo apt without any prompts.
This usage may be obsolete today, as most commands that would request response from the user have either a 'force' option (e.g., rm -f) or an 'assume-yes' option (for example,apt -y).
As an example, the following:
$ rm -f *.txt
is functionally equivalent to
$ yes | rm *.txt
The yes command in conjunction with the head command can be used to generate large volume files for means of testing. For example, executing
$ yes 1234567 | head -n1000 > file
results in a file consisting of 1000 lines each consisting of eight characters (1, 2, 3, 4, 5, 6, 7 and newline).
yes can be used as an easy way of generating CPU load. In 2006, for example, the yes command received publicity for being a means to test whether or not a user's MacBook is affected by the "Intermittent Shutdown Syndrome" bug, where a MacBook would randomly shut off without any user input. By running the yes command indefinitely twice via Terminal under Mac OS X, users were able to max out their computer's CPU, and thus see if the failure was heat related.[4][5]
Implementation and performance
[edit]The implementation of yes on different Unix and Unix-likes was consistently implemented with a simple while-loop. The GNU Project's implementation of yes was much faster than any other implementation, achieved by buffering its output, leading to more output per system call.[6][7] GNU's implementation may have been different to avoid infringing on the Unix copyright[original research?]. The FreeBSD Project changed their implementation in 2017 to match GNU's implementation.[8]
References
[edit]- ^ – Linux User Commands Manual
- ^ CoreUtils for Windows
- ^ Native Win32 ports of some GNU utilities
- ^ "Test for MacBook Random Shutdown Syndrome (RSS)". ZDNet. 2006-08-29. Archived from the original on June 5, 2010. Retrieved 2012-05-09.
- ^ "Testing your MacBook for Random Shut Downs". the apple files. 2006-08-02. Archived from the original on 2007-02-10. Retrieved 2008-01-16.
- ^ Endler, Matthias (2017-10-10). "A Little Story About the 'yes' Unix Command". Endler.dev. Archived from the original on 2022-01-25.
- ^ kjensenxz (2017-06-13). "r/unix - How is GNU 'yes' so fast?". Reddit. Archived from the original on 2021-10-30.
- ^ gahr (2017-06-13). "Improve yes' throughput" (commit). github.
Further reading
[edit]- Montfort, Nick (January 2012). The Trivial Program "yes" (PDF) (Technical report). Cambridge, Massachusetts: Trope Tank. 12-01. Retrieved 2022-02-08.
External links
[edit]- Manpage for
yes(GNU version) - GNU coreutils yes.c implementation
- FreeBSD yes.c implementation
- NetBSD yes.c implementation
- OpenBSD yes.c implementation
Yes (Unix)
View on Grokipediayes is a command-line utility in Unix and Unix-like operating systems that continuously outputs a specified string, or "y" by default, followed by a newline until interrupted or killed.[1] It serves primarily as a tool for automating affirmative responses in interactive scripts or programs that prompt for user input, such as confirmations requiring a "yes" reply.[2]
The command originated in the Seventh Edition of Research Unix (V7), released by Bell Laboratories in January 1979, where its source code consists of a minimal C program featuring an infinite loop that prints the default string or the first command-line argument.[3] This early implementation, lacking options, exemplifies the simplicity of early Unix tools designed for efficiency on limited hardware like the PDP-11.[4] In modern distributions, yes is included in the GNU coreutils package, which adds standard options like --help and --version, and employs buffering techniques to achieve high output throughput.[1]
Beyond automation, yes finds use in testing and data generation.[2] Although not part of the POSIX standard, it remains a ubiquitous utility across Linux, BSD, and other Unix variants, underscoring its enduring practicality in command-line workflows.
History and Development
Origins in Early Unix
Theyes command was introduced as part of Version 7 Unix, released by Bell Laboratories in January 1979.[5] This edition marked a significant milestone in Unix development, incorporating the first public release of the Bourne shell and expanding the system's utility set for scripting and system administration tasks. The command served as a basic tool for generating continuous output streams, addressing the need for automated input in early Unix environments where interactive prompts were common in batch jobs and script execution.[3]
Authored by Ken Thompson, the original implementation lacks a formal author credit in its source code or documentation.[3][6] The V7 source file, yes.c, is a minimalist C program consisting of an infinite loop that uses printf to repeatedly output "y" followed by a newline, or an alternative string if provided as an argument.[3] This design reflected the philosophy of Unix utilities: small, focused programs that could be composed via pipes and redirection to handle repetitive tasks efficiently in resource-constrained systems like the PDP-11.
The command remained largely unchanged through subsequent AT&T releases, such as System III (1981) and System V (1983), supporting the ecosystem's emphasis on modular, composable software components.
Standardization and Portability
Theyes command is not included as a required utility in the POSIX.1-2008 standard's Shell and Utilities volume, nor in the corresponding Single UNIX Specification (SUSv4). This absence means there is no formal specification for its behavior or interface in these standards, distinguishing it from other core shell utilities like echo or cat. Despite this, the command's simple design has facilitated its widespread adoption as a de facto standard tool in Unix-like environments, ensuring consistent availability without reliance on official ratification.
The yes command is present across major Unix variants, including AT&T System V releases from the 1980s onward, BSD derivatives such as FreeBSD and NetBSD, Linux distributions via the GNU coreutils package, and Apple's macOS through its BSD subsystem. In Linux, it has been part of the coreutils since the project's early versions in the late 1980s, providing a stable implementation that aligns with traditional Unix behavior. On macOS, the command follows the BSD heritage, offering the same basic functionality as seen in other POSIX-compliant systems, though without mandatory conformance requirements. This broad presence in System V, BSD, and GNU-based systems underscores its portability, allowing scripts and tools to invoke it reliably on most Unix-like platforms without modification.
Beyond Unix-like systems, GNU coreutils provides implementations of yes for non-Unix environments, including Windows via distributions like GnuWin32 and UnxUtils, as well as cross-platform toolchains such as Cygwin and MSYS2. These ports maintain compatibility with the traditional Unix semantics, enabling the command's use in mixed-environment development and testing workflows. The GNU version, in particular, ensures backward compatibility with earlier Unix implementations, supporting its role in portable scripting even outside native Unix contexts.
Although lacking a formal specification date like the 2008 POSIX.1 update, the command's portability stems from its inclusion in influential toolsets dating back to the 1970s in early Unix versions, with modern distributions preserving this legacy through projects like GNU coreutils (first released in 1987). This informal standardization via common practice has made yes ubiquitous, often treated as essential despite its non-mandatory status in official standards.
Command Syntax and Behavior
Basic Syntax
Theyes command in Unix-like systems is invoked using the basic syntax yes [string], where the optional string argument specifies the text to output repeatedly, followed by a newline character.[7] If no argument is provided, the command defaults to outputting the string "y" followed by a newline indefinitely.[1] This behavior ensures the command produces a continuous stream suitable for automation or testing scenarios requiring repetitive input.
When multiple strings are provided as arguments, such as yes string1 string2, the command outputs all strings concatenated on a single line, separated by single spaces, followed by a newline, and repeats this line indefinitely.[1] Providing an empty string, as in yes "", results in the output of solely newline characters, creating blank lines in a continuous loop.[1] Note that argument handling may vary slightly across implementations; for instance, traditional BSD systems typically accept only a single string argument, treating it as the sole output text.[7]
The yes command operates without any mandatory options under POSIX guidelines, as it is not formally defined in the POSIX standard (IEEE Std 1003.1). However, implementations like GNU Coreutils include optional extensions such as --help to display usage information and --version to show the program version, both of which cause the command to exit immediately after providing the requested output.[1] To pass an argument beginning with a hyphen (e.g., -foo), precede it with -- to prevent interpretation as an option.
By design, yes runs indefinitely until externally interrupted, such as via Ctrl+C (generating SIGINT) or closure of an output pipe, at which point it terminates normally with an exit status of 0.[1] In cases of write errors, such as a full output buffer, it exits with status 1.[1] This persistent execution model underscores its role as a simple, unbounded output generator.
Output Characteristics
Theyes command outputs its specified string—or the default "y" if no string is provided—continuously to standard output (stdout), appending a newline character after each iteration, forming an infinite stream of lines until the process is terminated by the user, a signal, or closure of the output stream.[2]
In pipeline scenarios, yes generates output indefinitely until the downstream command consumes all available input and exits, at which point the pipe closes and yes terminates; there are no inherent volume limits or throttling mechanisms built into the command itself.[2]
Among edge cases, invoking yes without any arguments produces repeated lines of "y" followed by a newline, while specifying an empty string (e.g., yes "") results in output consisting solely of newlines, creating empty lines. Special characters within the provided string are output literally without interpretation or escaping, preserving the exact content as specified. When redirected, such as to a file (e.g., yes > output.txt) or /dev/null (e.g., yes > /dev/null), the command continues writing to the redirected stdout until interrupted, potentially filling storage or consuming resources accordingly.[2]
This consistent and predictable behavior, with the default affirmative "y" response and no variation in output format, renders yes particularly suitable for automating yes/no prompts in interactive scripts or tools without requiring conditional logic.[2]
Practical Applications
Automating User Input
Theyes command serves as a fundamental tool for automating responses to interactive prompts in Unix-like systems, particularly by piping its output to other commands that require affirmative or repetitive user input. By default, it repeatedly outputs the string "y" followed by a newline until interrupted, allowing scripts or commands to proceed without manual intervention.[2] This is especially useful for commands like rm -i, which prompts for confirmation before deleting each file; piping yes enables non-interactive deletion, as in the example yes | rm -i file.txt, where the stream of "y" responses automatically approves all removals.[8][9]
In package management, yes has historically facilitated automated installations by responding to confirmation prompts, such as yes | apt-get install package-name, which would affirm the continuation query during dependency resolution and installation.[9] However, modern package managers like apt provide built-in non-interactive options, such as the -y or --assume-yes flag, which assumes affirmative responses to prompts and is generally preferred for its explicit control and safety checks against undesirable actions like removing essential packages.[10]
The command's integration into scripting enhances efficiency in automated workflows, including batch processing, cron-scheduled tasks, and deployment scripts, where it eliminates the need for human oversight on yes/no decisions, thereby streamlining repetitive operations in server environments or continuous integration pipelines.[9] For instance, in a deployment script, yes | ./configure && make install can automate build confirmations without pausing execution. Despite these benefits, yes is increasingly considered obsolete for many scenarios due to the prevalence of dedicated non-interactive flags in utilities like cp -f for forcing overwrites or rm -f for deletions without prompts, which offer more precise behavior.[8][10]
A key limitation of yes lies in its indiscriminate response generation, which can lead to unintended consequences, such as accidental data loss from overwriting files or installing unwanted packages without review, underscoring the importance of safeguards like testing in isolated environments or using flags that include abort conditions for critical errors.[9] This risk highlights why alternatives with built-in validations are favored in contemporary scripting practices.
Data Generation and Testing
Theyes command is commonly employed in Unix-like systems to generate repetitive output streams for creating dummy files during development and testing workflows. By piping its output to tools like head and redirecting to a file, users can quickly produce large volumes of test data without complex scripting. For instance, the command yes "test data" | head -n 1000 > file.txt creates a file containing 1000 lines of the string "test data", useful for simulating data files in application testing or populating directories for file system experiments.[11][12]
Beyond file creation, yes serves as a simple tool for CPU stress testing by maximizing processor utilization through continuous output generation. Redirecting its output to /dev/null, as in yes > /dev/null, discards the stream while keeping the CPU at near-100% load on a single core, allowing developers to evaluate system stability under heavy computational demand. This approach is particularly effective for single-threaded stress scenarios and can be extended across multiple instances to target multi-core systems.[13][14]
In 2006, the yes command gained notable attention for diagnosing hardware issues in early MacBook models affected by Intermittent Shutdown Syndrome, a thermal-related fault causing unexpected power-offs. Users and technicians ran multiple instances of yes in Terminal windows to simulate prolonged high CPU loads, heating the system to expose faulty thermal sensors within the warranty period; running two such processes for 10-24 hours helped identify vulnerable units prone to failure under normal intensive use like video encoding.[15]
Additionally, yes facilitates input generation for benchmarks and high-volume I/O simulations in development environments, where its infinite output can feed scripts or tools to test data processing pipelines or disk throughput. Combined with utilities like dd or piped directly, it enables rapid creation of repetitive content to assess I/O performance without specialized benchmarking software, providing a lightweight alternative for initial system evaluations.[16][13]
Implementation Details
Core Algorithm
The core algorithm of theyes command implements a simple infinite loop that continuously outputs a user-specified string (or a default value) followed by a newline character to standard output until the process is terminated. This design ensures relentless repetition, making it suitable for providing automated affirmative responses or generating streams of data. Implementations rely on basic control structures available in the C programming language, such as a while (true) loop, to achieve this behavior without conditional breaks in the primary execution path.[17]
String processing begins with command-line argument parsing: if no arguments are supplied, the default string "y" is selected; if arguments are present, the output string is formed by taking the first argument in traditional Unix implementations or by concatenating all arguments with intervening spaces in extended versions like GNU coreutils. This string is then appended with a newline for each iteration. The use of standard C library functions, such as strlen for length calculations and full_write (wrapping the POSIX write system call) for efficient output, promotes portability across Unix-like systems by adhering to POSIX-compliant interfaces.[17]
Interruptions are handled implicitly through the operating system's signal mechanisms and I/O error detection. Upon receiving SIGINT (typically from Ctrl+C), the process terminates via the default signal handler without setting an exit status; shells like bash report status 130, as no explicit signal handler is installed in basic implementations. Similarly, if output is piped to another process that closes the pipe, a write failure (e.g., returning a short count or error from full_write or equivalent) triggers an exit with status 1, ensuring graceful termination without leaving hanging processes.[17]
The fundamental logic can be represented in the following pseudocode, which captures the essence across implementations:
if no command-line arguments:
string = "y"
else:
string = process_arguments() // e.g., first arg or concatenated args
while true:
output(string + "\n")
if output fails (e.g., pipe closed):
exit with status 1
if no command-line arguments:
string = "y"
else:
string = process_arguments() // e.g., first arg or concatenated args
while true:
output(string + "\n")
if output fails (e.g., pipe closed):
exit with status 1
Performance Optimizations
The GNU coreutils implementation of theyes command achieves high throughput by employing buffered output, utilizing a buffer size of at least the BUFSIZ constant (typically 8192 bytes or 8 KB), which is filled with repeated copies of the output string including newlines to reduce the frequency of system calls.[18][19] This approach contrasts with unbuffered output methods, enabling significantly faster performance, often reaching 4-5 GB/s on modern hardware with sufficient memory bandwidth.[20][21]
In FreeBSD, the yes command underwent a key update in June 2017 to incorporate GNU-like buffering, replacing unbuffered writes with a strategy that packs multiple lines into larger output blocks.[21] Prior to this change, FreeBSD's implementation achieved around 140 MB/s; the update roughly doubled throughput to approximately 280 MB/s, though speeds on contemporary hardware can exceed 1 GB/s depending on system capabilities.[20][21]
Several factors influence the performance of yes across Unix-like systems, including I/O bottlenecks such as pipe buffer sizes or disk write speeds, which cap overall throughput regardless of CPU efficiency.[22] CPU utilization remains low during normal operation, as the process blocks on I/O when output cannot be immediately consumed, preventing wasteful spinning in the loop.[23] On embedded devices with constrained resources, such as limited RAM or slower processors, performance degrades notably, often to tens of MB/s, due to reduced memory alignment and I/O handling capabilities.[24]
Recent Linux kernel developments in the 2020s have introduced optimizations for pipe handling that benefit high-output commands like yes, including refinements to buffer management and wait mechanisms to minimize latency in data transfer.[22] For instance, a 2020 patch by Linus Torvalds for Linux kernel 5.6 enhanced pipe code to use exclusive waits, reducing contention in multi-process scenarios and improving aggregate throughput.[25] In mobile Unix-like environments such as Android, where yes may be used in scripts, energy efficiency is enhanced by the command's I/O-bound nature, which avoids continuous CPU activity and thus minimizes battery drain compared to active polling loops.[23]