Hubbry Logo
Fortune (Unix)Fortune (Unix)Main
Open search
Fortune (Unix)
Community hub
Fortune (Unix)
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Fortune (Unix)
Fortune (Unix)
from Wikipedia
fortune
Original authorKen Arnold
Initial release1979; 47 years ago (1979)
Written inC
Operating systemUnix, Unix-like, Plan 9, Inferno
TypeCommand
LicensePlan 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]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
fortune is a command-line utility in operating systems that selects and displays a pseudorandom , , or from a predefined database of such entries known as "fortunes." The program originated in released in 1979 by , where it provided simple random output from categorized text files. 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 screens, terminals, and recreational use. 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.

History

Origins in Early Unix

The fortune program first appeared in Version 7 Unix, released by AT&T Bell Laboratories in January 1979. 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. 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. In its original form, fortune operated as a straightforward command that selected and displayed a pseudorandom or from a simple database, typically containing brief, witty, or philosophical statements. Without indexing mechanisms or options for customization, it relied on basic —likely seeded by or process ID—to pick entries, printing one upon invocation with no arguments. The associated data files in Version 7 were minimal, comprising a small collection of without subdivisions by theme, length, or tone, distinguishing this precursor from subsequent enhancements. Developed amid the serious pursuits of operating system refinement at , the program provided a touch of levity in terminal sessions dominated by programming tasks, aligning with the research-oriented that prioritized and ingenuity over rigid functionality. Its presence in the games section of the Version 7 distribution underscored its role as an ancillary tool rather than a essential, embodying early Unix's balance of and programmer amusement.

Development of the BSD Version

Ken Arnold, a at the , developed an enhanced version of the fortune program around the end of 1978, building on earlier implementations from . This BSD-specific iteration introduced greater sophistication, including mechanisms for handling multiple fortune databases and improved random selection processes tailored to the growing ecosystem. A key innovation was the integration of the strfile 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. This addressed performance limitations in earlier versions, particularly as fortune databases expanded to include thousands of entries across categories. Support for categorized output was also added, allowing users to select subsets like , humor, or aphorisms from segregated files, reflecting a modular approach to data organization. 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 hardware. 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.

Technical Functionality

Core Mechanism and Pseudorandom Selection

The 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 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). To select an entry, the program reads the total count from the index header and generates a pseudorandom 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 stream accordingly and outputs the content up to the (usually a % line or file end). In contemporary BSD-derived implementations, such as , the random is derived via arc4random_uniform(), which leverages a system-seeded initialized from kernel pools rather than a simple time-based seed. This index-driven approach enables sub-millisecond access times for large containing thousands of entries, as direct file seeks replace linear searches. The absence of a user-supplied in standard invocations—relying instead on opaque system —prevents deterministic reproduction across runs, fostering the tool's intended unpredictability while maintaining computational efficiency and alignment with Unix conventions for lightweight, stateless utilities.

Fortune File Structure and Indexing

Fortune databases are stored in files where individual entries—typically short quotations, aphorisms, or humorous remarks—are delimited by lines containing only a single '%' character. 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. This format ensures straightforward parsing, with the '%' acting as a clear boundary to separate discrete pieces of content. To facilitate efficient retrieval, the strfile utility processes these text files and generates a binary index file with the .dat extension. 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 . 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. 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. The modular design permits easy extension through additional files, as the fortune program can reference multiple indexed databases via configuration or invocation.

% 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

In the example above, the single-line fortune is bounded by '%' delimiters, while multi-line entries follow the same convention by including intervening lines as part of the preceding fortune. The 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. 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.

Command Usage

Basic Invocation and Output

The fortune command is invoked without arguments by typing fortune in a , prompting it to select and print a single pseudorandom from the default database of quotations. 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 . Execution outputs the chosen epigram directly to standard output in the terminal, consisting of a concise , 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. This ephemeral, non-interactive display aligns with the command's design for standalone, lightweight use in terminal sessions. For example, a run might produce: "Computers are useless. They can only give you answers." -- , drawn from the general fortunes pool. To draw from a specific file or category, the command accepts a or directory path as an , such as fortune idioms to restrict selection to idiom-related entries if idioms.dat exists in the search path. Default behavior weights selections by file contents unless modified, ensuring varied output across invocations while maintaining simplicity verifiable in man pages across systems.

Available Options and Flags

The fortune command provides command-line options to filter fortunes by category, , 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. 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. 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. 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). 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. 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 scripts. Variants may offer -q to suppress trailing separators for cleaner, script-friendly output, though this is not universal across implementations.
OptionDescription
-aSelect from all categories, including offensive.
-oOffensive fortunes only.
-lLong fortunes only (above threshold).
-sShort fortunes only (below threshold).
-n <length>Set short/long threshold in characters (default: 160).
-fList files without displaying fortune.
-eEqual weighting for all files.
-wWait after output based on length.

Content and Databases

Standard Quote Collections

The standard quote collections in original Unix distributions, such as those in from 1979 and subsequent BSD releases up to 4.4BSD, are stored in files like fortunes, featuring aphorisms, proverbs, literary excerpts, and insights on . These entries, delimited by lines containing a single (%), emphasize themes of , humor, , and irony, often presenting concise observations on life, , and . 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 and in system design. 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 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.

Offensive and Custom Fortunes

The -o option of the fortune command selects from a dedicated database of potentially offensive aphorisms, which encompass , crude sexual jokes, satirical commentary on and , and other irreverent content deemed unsuitable for general audiences. These fortunes originated in early BSD distributions during the late and , 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. 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. 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 % or blank lines—using the strfile utility, which generates a .dat index for efficient , then place the resulting pair in system directories like /usr/share/games/fortunes. Examples abound in open repositories, such as compilations of aphorisms or sysadmin troubleshooting tips, allowing tailored morale boosts or educational quips in professional environments. This extensibility preserves the tool's roots in user-driven customization, countering modern efforts to excise offensive material—evident in distributions like , which removed such databases entirely for its 2025 release—by enabling communities to maintain archives of the original unfiltered variants.

Implementations and Variants

Original AT&T and BSD Implementations

The fortune program originated in 's Version 7 Unix, released on January 9, 1979, as a simple utility for displaying pseudorandom quotations from text files. 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. 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 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. Arnold's implementation introduced the strfile utility for preprocessing fortune files into indexed databases, enabling rapid without full scans—critical for multi-user systems at UC Berkeley, where simultaneous logins from numerous students and researchers imposed demands. 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. 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 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.

GNU Fortune and Linux Distributions

The fortune-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. 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. This version receives ongoing updates, with releases such as 3.24.0 in 2024 adding optional compile-time features like support for alternative generators while maintaining with existing fortune databases. of active maintenance is evident in its packaging status across repositories, where version tracking and build logs confirm regular integrations and security patches. fortune-mod is distributed in prominent Linux distributions, including —where it provides the core program and data preparation utilities in the fortune-mod package—and , via the Extra repository, facilitating easy installation and use by millions of users worldwide. Similarly, it appears in and other derivatives through Launchpad, underscoring its role in enhancing terminal-based utilities without dependency on proprietary code. By employing permissive licensing such as BSD-4-Clause-UC, fortune-mod aligns with 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. 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.

Ports and Modern Reimplementations

Fortune has been adapted for Windows through POSIX emulation layers like , which includes implementations of Unix utilities enabling the program's execution in a command-line environment mimicking BSD behavior. Independent ports bypass such layers by reimplementing core logic in portable languages; Python packages on PyPI, such as fortune and lfortune, provide stripped-down versions that generate indexed random quotations without requiring Unix system calls. Mobile adaptations include Android applications like the Fortunes viewer available on , which displays Unix-style fortunes from bundled or user-added files, supporting offline pseudorandom selection via device resources. Open-source reimplementations on , notably HubTou/fortune as part of the Portable 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. Source inspection confirms adaptation for cross-platform compatibility, indexing fortune databases with dat files and selecting entries probabilistically proportional to length, akin to originals. 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.

Cultural Role and Criticisms

Influence on Unix and Hacker Culture

The fortune program, originating in (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 . 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. These fortune cookies often encapsulated hacker values through content drawn from sources like Murphy's Laws, Zen koans, or satirical commentary on programming and , thereby disseminating an of irreverence toward overly rigid systems, appreciation for elegant in tools, and recognition of human fallibility in computation. 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. 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. 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 documentation as recent as 2025 affirms its ongoing invocation in terminals for similar morale-boosting effects.

Controversies Over Content and Relevance

Criticisms of the fortune program's content have centered on its inclusion of quotes deemed , profane, or otherwise offensive, reflecting the unfiltered humor of its 1970s origins in Unix . A May 15, 2015, discussion on Reddit's r/unixporn subreddit highlighted user frustration with perceived in the quotes, with participants noting that the distribution had preemptively removed offensive entries to avoid such issues, leading some to seek alternative collections. Similar concerns persisted, as evidenced by a , 2022, Launchpad bug report against the fortunes-off package in , which documented instances of racist, misogynist, homophobic, and fascist material, including quotations, prompting calls for excision. These critiques often stem from modern sensibilities clashing with the program's historical edginess, where sanitization efforts—such as Debian's August 4, 2025, removal of select "offensive" quotes in Spanish and Italian fortune files—are defended by maintainers as aligning with community standards but criticized by others as imposing contemporary biases on archival software. Defenders of the unfiltered originals argue that such content preserves the authentic, irreverent spirit of early Unix development, where humor served as a to technical drudgery without deference to later norms. Projects like the GitHub repository "misfortune" explicitly compile "offensive" excluded from mainstream distributions, framing their removal as overreach that erodes cultural fidelity to the program's intent. Empirical evidence of demand includes ongoing user efforts, such as October 2024 Reddit queries on reinstalling offensive fortunes in despite build-time disables, and January 2024 successes in integrating them into screensavers, indicating that a subset of CLI enthusiasts values historical completeness over filtered outputs. While no formal studies quantify gains from the humor, anecdotal preservation efforts underscore a causal link between retaining edgy quotes and maintaining the tool's role as a booster in terminal-based workflows. Debates over relevance in the graphical user interface (GUI) era question whether random quips enhance or distract from modern , particularly in shared or environments where offensive outputs risk alienating users. Proponents contend that fortune's persistence in command-line interfaces across distributions sustains Unix traditions amid GUI dominance, potentially aiding focus through brief levity, though no aggregated data confirms net productivity benefits. Critics advocate configurable filters or opt-in offensives to mitigate interpersonal conflicts, as seen in distribution policies, yet unfiltered variants arguably better uphold causal realism in software by avoiding retroactive that distorts empirical records of past developer norms.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.