Recent from talks
Nothing was collected or created yet.
Fortune (Unix)
View on WikipediaThis article needs additional citations for verification. (October 2010) |
| fortune | |
|---|---|
| Original author | Ken Arnold |
| Initial release | 1979 |
| Written in | C |
| Operating system | Unix, Unix-like, Plan 9, Inferno |
| Type | Command |
| License | Plan 9: MIT License |
| Repository | |
fortune is a program that displays a pseudorandom message from a database of quotations.
Early versions of the program appeared in Version 7 Unix in 1979.[1]
The most common version on modern systems is the BSD fortune, originally written by Ken Arnold.[2] Distributions of fortune are usually bundled with a collection of themed files, containing sayings like those found on fortune cookies (hence the name), quotations from famous people, jokes, or poetry.
fortune is predominantly found on Unix-like systems, but clients for other platforms also exist.[3] Often, users on text-mode Unix terminals will place this command into either their .profile or .logout files to display them at logon and logout, respectively. It is also used to generate text input for certain XScreenSaver modes.
Content
[edit]Most Unix systems use fortunes which are slanted heavily toward the user base of Unix, and thus contain many obscure jokes about computer science and computer programming. Other favoured sources include quotations from science fiction (Star Trek, The Cyberiad, Doctor Who, The Hitchhiker's Guide to the Galaxy, etc.), Zippy the Pinhead, and the writings of Ambrose Bierce and Dave Barry.[4] Most fortune collections also include a wide variety of more conventionally sourced quotations, jokes, and other short passages. A few distributions include "offensive" dicta, which require the -a or -o options to be passed for viewing. These fortunes often include rude humor and profanity, personal attacks, and controversial comments about religion. Sometimes they are provided by another package, however as of FreeBSD 10.0 the offensive dicta have been removed completely.[5]
As of November 2017, the quotations (with the exception of tips relevant to system operation) have been removed from FreeBSD entirely after user complaints regarding quotations from Adolf Hitler being contained in some of the files.[6]
The exact fortunes vary between each type of Unix, however there seems to be a strong overlap between the FreeBSD and OpenBSD fortune files. The Plan 9 fortune files seem to be much shorter, with many just on 1 line, and the 'offensive' dicta is much stronger. Most Linux distributions, such as Debian (and its derivatives), choose the FreeBSD fortunes to put in their fortune packages, that can be installed through the package manager.
Purpose
[edit]One of the included fortunes, from the "goedel" collection of fortunes about fortune itself, sums up the purpose of the program:
Has anyone realized that the purpose of the fortune cookie program is to
defuse project tensions? When did you ever see a cheerful cookie, a
non-cynical, or even an informative cookie?
Perhaps inadvertently, we have a channel for our aggressions. This
still begs the question of whether the cookie releases the pressure or only
serves to blunt the warning signs.
Long live the revolution!
Have a nice day.
The original fortune program could be used for the more general task of picking up a random line from a plain-text file.[7] However, in most modern Unix systems fortune cannot be used this way, since they use an ad hoc file format for fortune files to allow multiline aphorisms.
Fortune files
[edit]Conventional versions of fortune use two files for each quotation list: a text file with quotations, each separated by the character "%" on its own line, and a random-access data file generated by the strfile(1) program. Alternative implementations, including those made for display on Web pages, typically use only the text file.
Common options
[edit]Several common options exist that change the way command-line versions of fortune behave:
| Option | Action |
|---|---|
-a
|
Choose from all databases, regardless of whether they are considered "offensive" or not |
-e
|
Make the probability of choosing a fortune file equal to that of all other files |
-f
|
Print out a list of all fortune files that would have been searched, but do not print a fortune |
-i
|
When used with -m, make regular expression searching case-insensitive
|
-l
|
Use only quotations longer than the length specified with -n, or 160 characters if -n is not used
|
-m [pattern]
|
Print all fortunes matching the regular expression specified in [pattern]
|
-n [length]
|
Override the length used by -l and -s to determine "long" and "short" messages (default 160 characters)
|
-o
|
Choose only from "offensive" databases |
-s
|
Use only quotations shorter than the length specified with -n, or 160 characters if -n is not used
|
-w
|
Wait for a period of time before terminating; useful for situations in which a fortune needs to be read before the screen is cleared |
See also
[edit]References
[edit]- ^ "V7/usr/src/games/fortune.c". tuhs.org. Retrieved 2024-02-10.
- ^ "[base] Contents of /head/usr.bin/fortune/fortune/fortune.c". svnweb.freebsd.org. Retrieved 2018-09-15.
This code is derived from software contributed to Berkeley by Ken Arnold.
- ^ "Jar of Fortune Files". fortunes.cat-v.org.
- ^ "Debian Sources: fortune 1:1.99.1-7, "datfiles" folder". sources.debian.org. Retrieved 2018-09-15.
- ^ "Fortune - removal log". FreeBSD SVN. FreeBSD. 2013-03-12. Retrieved 2014-06-14.
- ^ "[base] Revision 325828". svnweb.freebsd.org. 2017-11-14. Retrieved 2018-04-14.
- ^ Tom Duff. "rc documentation". plan9.bell-labs.com. Archived from the original on 2014-09-08.
First, the program guesses a location (in
$lab) using thefortuneprogram to pick a random line from the location list.
External links
[edit]- – Plan 9 Programmer's Manual, Volume 1
- – Linux Games Manual
- A PHP version of the fortune program
- The manual page for the original Unix fortune(6) command.
- Maintenance version of fortune-mod's source code - on GitHub with new releases
- "FTP link". ftp.ibiblio.org. Archived from the original on 2021-01-15. – source code for fortune-mod program
- A wiki containing all of the original non offensive fortunes
- A modern, color-terminal oriented fortune database
- A fortune-mod add on for math-related fortunes
- A portable and full implementation in Python, distributed with all the classical and historical cookie files
Fortune (Unix)
View on Grokipediafortune is a command-line utility in Unix-like operating systems that selects and displays a pseudorandom epigram, aphorism, or quotation from a predefined database of such entries known as "fortunes."[1][2] The program originated in Version 7 Unix released in 1979 by Bell Labs, where it provided simple random output from categorized text files.[3] Its BSD variant, developed by Ken Arnold around 1978 and distributed with 4BSD, introduced enhanced features including datbase indexing via strfile for efficient random selection and categorization into subsets like humorous, offensive, or literary quotes, making it a staple in Unix environments for login screens, terminals, and recreational use.[4][3] Modern distributions often include extensive fortune collections amassed over decades, with options to filter by length, category, or equality of chances, though some entries reflect dated humor or biases inherent to their era of collection.[5]
History
Origins in Early Unix
Thefortune program first appeared in Version 7 Unix, released by AT&T Bell Laboratories in January 1979.[6] This edition marked the culmination of internal research efforts at Bell Labs, where Unix had evolved from earlier versions into a more portable and feature-rich system distributed to universities and select licensees.[7] The program's inclusion reflected the informal, experimental culture of Unix development at the labs, where utilities often incorporated lightweight, non-essential elements alongside core tools for file management, editing, and compilation.[8]
In its original form, fortune operated as a straightforward command that selected and displayed a pseudorandom epigram or quotation from a simple text file database, typically containing brief, witty, or philosophical statements.[3] Without indexing mechanisms or options for customization, it relied on basic random number generation—likely seeded by system time or process ID—to pick entries, printing one upon invocation with no arguments.[6] The associated data files in Version 7 were minimal, comprising a small collection of fortunes without subdivisions by theme, length, or tone, distinguishing this precursor from subsequent enhancements.[3]
Developed amid the serious pursuits of operating system refinement at Bell Labs, the program provided a touch of levity in terminal sessions dominated by programming tasks, aligning with the research-oriented ethos that prioritized utility and ingenuity over rigid functionality.[9] Its presence in the games section of the Version 7 distribution underscored its role as an ancillary tool rather than a productivity essential, embodying early Unix's balance of pragmatism and programmer amusement.[10]
Development of the BSD Version
Ken Arnold, a programmer at the University of California, Berkeley, developed an enhanced version of the fortune program around the end of 1978, building on earlier implementations from Version 7 Unix.[3] This BSD-specific iteration introduced greater sophistication, including mechanisms for handling multiple fortune databases and improved random selection processes tailored to the growing Berkeley Software Distribution ecosystem.[3] A key innovation was the integration of thestrfile utility, which Arnold created to generate index files (with .dat extensions) from plain-text fortune files, enabling efficient pseudorandom access to individual entries without requiring sequential file scans.[11] This addressed performance limitations in earlier versions, particularly as fortune databases expanded to include thousands of entries across categories.[6] Support for categorized output was also added, allowing users to select subsets like literature, humor, or aphorisms from segregated files, reflecting a modular approach to data organization.[11]
The BSD fortune was first released as part of 4BSD in November 1980, with further refinements appearing in 4.1cBSD around 1982, facilitating its widespread adoption in academic and research environments running VAX hardware.[3] These enhancements aligned with BSD's emphasis on practical tools for system administrators and developers, providing brief, randomized textual output to inject levity into routine command-line interactions amid extended programming sessions.[6]
Technical Functionality
Core Mechanism and Pseudorandom Selection
Thefortune command employs a pseudorandom selection process to retrieve a single entry from its database of delimited quotes, ensuring unbiased output without sequential scanning of the full dataset. This mechanism relies on binary index files, typically with a .dat extension, which are pre-generated from the quote data files using the strfile utility; these indices store offsets to each fortune's start and end positions, along with a header indicating the total number of entries (str_numstr).[12][11]
To select an entry, the program reads the total count from the index header and generates a uniform pseudorandom integer in the range [0, str_numstr - 1]. It then seeks to the corresponding slot in the index file to obtain the byte offsets, after which it positions the data file stream accordingly and outputs the content up to the delimiter (usually a % line or file end). In contemporary BSD-derived implementations, such as FreeBSD, the random integer is derived via arc4random_uniform(), which leverages a system-seeded pseudorandom number generator initialized from kernel entropy pools rather than a simple time-based seed.[11]
This index-driven approach enables sub-millisecond access times for large databases containing thousands of entries, as direct file seeks replace linear searches. The absence of a user-supplied seed in standard invocations—relying instead on opaque system entropy—prevents deterministic reproduction across runs, fostering the tool's intended unpredictability while maintaining computational efficiency and alignment with Unix conventions for lightweight, stateless utilities.[11][12]
Fortune File Structure and Indexing
Fortune databases are stored in plain text files where individual entries—typically short quotations, aphorisms, or humorous remarks—are delimited by lines containing only a single '%' character.[13] Each entry begins immediately after a '%' delimiter (or at the file's start for the first one) and continues across one or more lines until the next standalone '%' line, allowing multi-line fortunes without additional markers.[13] This format ensures straightforward parsing, with the '%' acting as a clear boundary to separate discrete pieces of content. To facilitate efficient retrieval, thestrfile utility processes these text files and generates a binary index file with the .dat extension.[13] The index records byte offsets for each fortune's starting position in the source file, enabling the fortune program to perform direct seeks rather than linear scans of potentially large databases.[14] When invoked, strfile scans the input for '%' delimiters, computes the necessary offsets, and outputs a structured .dat file containing a header with metadata (such as the number of entries and longest fortune length) followed by the offset table.[13]
This structure supports categorization by maintaining separate text files for different collections, each paired with its own .dat index; for instance, a general-purpose file named fortunes can coexist with fortunes-o for offensive entries flagged via the -o option in strfile, which embeds an 'O' indicator in the index for optional filtering.[13] The modular design permits easy extension through additional files, as the fortune program can reference multiple indexed databases via configuration or invocation.[14]
%
A computer lets you make more mistakes faster than any other invention,
with the possible exceptions of handguns and [Tequila](/page/Tequila).
%
Murphy's Law
%
A computer lets you make more mistakes faster than any other invention,
with the possible exceptions of handguns and [Tequila](/page/Tequila).
%
Murphy's Law
strfile command is typically run as strfile [options] source.dat to produce source.dat.dat, though the output index shares the base name with an added .dat suffix for pairing.[13] This preprocessing step is essential for performance in systems with extensive fortune collections, dating back to the utility's inclusion in BSD Unix distributions since the early 1980s.[13]
Command Usage
Basic Invocation and Output
Thefortune command is invoked without arguments by typing fortune in a Unix shell, prompting it to select and print a single pseudorandom epigram from the default database of quotations.[1] This database comprises multiple categorized files, typically stored in /usr/share/fortunes/ or /usr/games/fortunes/ depending on the system implementation, with entries separated by % delimiters for efficient random access.[1][15]
Execution outputs the chosen epigram directly to standard output in the terminal, consisting of a concise quotation, adage, or witty remark—often one to several lines long—potentially followed by an author attribution, after which the command exits without further interaction or data persistence.[1] This ephemeral, non-interactive display aligns with the command's design for standalone, lightweight use in terminal sessions.[1] For example, a run might produce: "Computers are useless. They can only give you answers." -- Pablo Picasso, drawn from the general fortunes pool.[1]
To draw from a specific file or category, the command accepts a filename or directory path as an argument, such as fortune idioms to restrict selection to idiom-related entries if idioms.dat exists in the search path.[1] Default behavior weights selections by file contents unless modified, ensuring varied output across invocations while maintaining simplicity verifiable in man pages across Unix-like systems.[1]
Available Options and Flags
Thefortune command provides command-line options to filter fortunes by category, length, or content type, enabling targeted selection from databases that may span thousands of entries across multiple files. These flags adjust the pseudorandom selection process by restricting the eligible pool, such as excluding non-offensive content or applying length thresholds, which proportionally reduces output variability for repeated invocations.[2][1]
The -a option includes all fortune categories in the selection, encompassing both standard and offensive databases that are segregated by default to avoid unintended exposure to potentially controversial material.[2] In contrast, the -o flag confines output to offensive fortunes only, sourcing exclusively from designated files and thereby limiting the pool to a subset often characterized by irreverent, satirical, or provocative aphorisms.[2]
Length-based filtering is handled by -l for long dictums only and -s for short apothegms only, with the -n argument setting the character threshold distinguishing short from long (defaulting to 160 characters).[1] For example, fortune -l excludes brief entries under the threshold, favoring more substantive quotes and altering the average output length accordingly. The -f option lists searchable fortune files without generating output, aiding verification of database availability and composition prior to selection.[1][2]
Additional modifiers include -e, which treats all fortune files as equal weight regardless of entry count, promoting uniform probability across databases of varying sizes, and -w, which pauses post-display proportional to the fortune's length to facilitate reading in interactive sessions like login scripts.[1][2] Variants may offer -q to suppress trailing separators for cleaner, script-friendly output, though this is not universal across implementations.[16]
| Option | Description |
|---|---|
-a | Select from all categories, including offensive.[2] |
-o | Offensive fortunes only.[2] |
-l | Long fortunes only (above threshold).[1] |
-s | Short fortunes only (below threshold).[1] |
-n <length> | Set short/long threshold in characters (default: 160).[1] |
-f | List files without displaying fortune.[1] |
-e | Equal weighting for all files.[2] |
-w | Wait after output based on length.[2] |
Content and Databases
Standard Quote Collections
The standard quote collections in original Unix distributions, such as those in Version 7 Unix from 1979 and subsequent BSD releases up to 4.4BSD, are stored in plain text files likefortunes, featuring aphorisms, proverbs, literary excerpts, and insights on Unix philosophy. These entries, delimited by lines containing a single percent sign (%), emphasize themes of wisdom, humor, wit, and irony, often presenting concise observations on life, technology, and human behavior.[6]
Sourced from public domain texts and historical writings, the collections include one-liner aphorisms for brevity and multi-line excerpts for depth, with early versions lacking binary indexing files and relying on sequential reads for random selection. Examples encompass proverbial sayings like those akin to traditional fortune cookies, alongside reflective Unix-centric insights that highlight principles of simplicity and modularity in system design.[6]
The number of entries varies by release—for instance, spanning multiple themed files across historical versions from January 1979 to June 1993—but typically comprises hundreds of distinct fortunes in core databases, expandable through additional category files without offensive content. These standard sets prioritize non-controversial, verifiable material from era-appropriate sources, ensuring compatibility with the program's pseudorandom output mechanism.[6]
Offensive and Custom Fortunes
The-o option of the fortune command selects from a dedicated database of potentially offensive aphorisms, which encompass profanity, crude sexual jokes, satirical commentary on religion and politics, and other irreverent content deemed unsuitable for general audiences.[17][12] These fortunes originated in early BSD distributions during the late 1970s and 1980s, aligning with the hacker culture's emphasis on unvarnished wit as a counter to institutional rigidity, where such material served to maintain morale among developers without regard for emerging sensitivities around language or topics.[6] Historical fortune databases from Unix versions between 1979 and 1993 include entries with explicit rude humor, underscoring the program's initial design to include boundary-pushing content rather than defaulting to sanitized selections.[6]
Custom fortune files enable users to extend the databases beyond standard collections, typically by compiling personal or domain-specific quotes into indexed formats compatible with fortune. To create such files, users compile plain-text entries—separated by a % delimiter or blank lines—using the strfile utility, which generates a .dat index for efficient random access, then place the resulting pair in system directories like /usr/share/games/fortunes. Examples abound in open repositories, such as compilations of Unix philosophy aphorisms or sysadmin troubleshooting tips, allowing tailored morale boosts or educational quips in professional environments.[18] This extensibility preserves the tool's roots in user-driven customization, countering modern efforts to excise offensive material—evident in distributions like Debian, which removed such databases entirely for its 2025 release—by enabling communities to maintain archives of the original unfiltered variants.[19]
Implementations and Variants
Original AT&T and BSD Implementations
Thefortune program originated in AT&T's Version 7 Unix, released on January 9, 1979, as a simple utility for displaying pseudorandom quotations from text files.[3] This initial implementation lacked indexing mechanisms, relying instead on sequential file scans to select entries, which limited efficiency in environments with larger databases or concurrent access.[3] The core mechanism involved basic pseudorandom number generation to pick offsets within unindexed fortune files, aligning with the resource-constrained hardware and single-user focus of early AT&T Unix systems. Source code from Version 7, preserved in archives like The Unix Heritage Society (TUHS), confirms this primitive structure, prioritizing minimalism over scalability.
Berkeley Software Distribution (BSD) advanced the program through Ken Arnold's contributions, with the enhanced version written around late 1978 and first released in 4BSD in November 1980.[3] Arnold's implementation introduced the strfile utility for preprocessing fortune files into indexed databases, enabling rapid random access without full scans—critical for multi-user systems at UC Berkeley, where simultaneous logins from numerous students and researchers imposed performance demands.[3] This indexing used compile-time generation of offset tables and checksums, reducing selection time from O(n) to near-constant, as evidenced in 4BSD sources. The design responded directly to real-world causal pressures in academic computing, such as avoiding system bottlenecks during peak usage, rather than theoretical ideals.[3]
These BSD features ensured greater reliability and speed in shared environments, with the program's integration into subsequent releases like 4.1BSD (1981) and 4.2BSD (1983) perpetuating its form. Historical TUHS repositories provide verifiable C source code for both AT&T and BSD variants, allowing direct comparison of their structural differences—AT&T's brevity versus BSD's added modularity for maintainability. No ideological motivations are documented; enhancements stemmed from empirical needs for operational efficiency in resource-limited, high-concurrency university settings.[3]
GNU Fortune and Linux Distributions
Thefortune-mod package serves as the primary free software adaptation of the Unix fortune utility for GNU/Linux environments, reimplementing the core pseudorandom selection and output logic from the original BSD implementation to ensure compatibility across modern systems.[20] Maintained by developer Shlomi Fish since at least 2011, it supports the standard fortune file formats, including plain text files with '%' delimiters and the associated .dat index files generated via the included strfile tool.[21]
This version receives ongoing updates, with releases such as 3.24.0 in 2024 adding optional compile-time features like support for alternative random number generators while maintaining backward compatibility with existing fortune databases.[22] Empirical evidence of active maintenance is evident in its packaging status across repositories, where version tracking and build logs confirm regular integrations and security patches.[23]
fortune-mod is distributed in prominent Linux distributions, including Debian—where it provides the core program and data preparation utilities in the fortune-mod package—and Arch Linux, via the Extra repository, facilitating easy installation and use by millions of users worldwide.[24][22] Similarly, it appears in Ubuntu and other derivatives through Launchpad, underscoring its role in enhancing terminal-based utilities without dependency on proprietary code.[25]
By employing permissive licensing such as BSD-4-Clause-UC, fortune-mod aligns with Free Software Foundation principles of source availability and modifiability, enabling inclusion in fully free distributions while preserving the unfiltered, humorous essence of the original fortunes, including optional offensive variants that some distributions handle via separate packages or flags.[26] This approach avoids content sanitization, prioritizing fidelity to the source material over external sensitivities, as evidenced by the retention of full databases in upstream releases.[21]
Ports and Modern Reimplementations
Fortune has been adapted for Windows through POSIX emulation layers like Cygwin, which includes implementations of Unix utilities enabling the program's execution in a command-line environment mimicking BSD behavior.[27] Independent ports bypass such layers by reimplementing core logic in portable languages; Python packages on PyPI, such asfortune and lfortune, provide stripped-down versions that generate indexed random quotations without requiring Unix system calls.[28][29]
Mobile adaptations include Android applications like the Fortunes viewer available on F-Droid, which displays Unix-style fortunes from bundled or user-added files, supporting offline pseudorandom selection via device resources.[30]
Open-source reimplementations on GitHub, notably HubTou/fortune as part of the Portable Unix-like tools project, recreate BSD fortune in pure Python, preserving pseudorandom output via language-native random modules while omitting fork-based output handling suited to non-process-spawning contexts like scripts or embedded systems.[3] Source inspection confirms adaptation for cross-platform compatibility, indexing fortune databases with dat files and selecting entries probabilistically proportional to length, akin to originals.[3]
Recent packages, such as fortune-package updated November 3, 2024, facilitate integration into habit-building tools or application loading screens by exposing random quotation APIs, underscoring sustained utility in non-terminal software.[31]
Cultural Role and Criticisms
Influence on Unix and Hacker Culture
Thefortune program, originating in Berkeley Software Distribution (BSD) Unix around 1978 and refined by Ken Arnold, gained ubiquity through its integration into user shell profiles like .login or .bashrc, where it would output pseudorandom quotations—termed "fortune cookies"—immediately upon terminal login.[6][32] This ritualistic display of trivia, maxims, jokes, or philosophical insights at session start blended Unix's emphasis on efficient tooling with an undercurrent of intellectual playfulness, serving as a daily reminder of the system's capacity for both productivity and diversion.[32]
These fortune cookies often encapsulated hacker values through content drawn from sources like Murphy's Laws, Zen koans, or satirical commentary on programming and bureaucracy, thereby disseminating an ethos of irreverence toward overly rigid systems, appreciation for elegant simplicity in tools, and recognition of human fallibility in computation.[32] By routinely exposing users to such material, the program reinforced cultural norms of skepticism, humor in adversity, and communal sharing of wit, which paralleled the collaborative, anti-authoritarian spirit animating early Unix development and later open-source communities.[32]
Archival accounts from hacker lexicography highlight fortune's endurance among "Unix power-culturati," as it persisted through the 1990s push toward graphical user interfaces that marginalized command-line traditions, thereby contributing to the sustained morale and loyalty within text-terminal-centric workflows over GUI-dominated alternatives.[32] This resilience underscores a causal role in preserving Unix's appeal as a hacker-friendly environment, where levity mitigated the austerity of prolonged interaction with sparse interfaces; contemporary Linux documentation as recent as 2025 affirms its ongoing invocation in terminals for similar morale-boosting effects.[33]
