Recent from talks
Contribute something
Nothing was collected or created yet.
Sleep (command)
View on Wikipedia| sleep | |
|---|---|
The sleep command | |
| Developers | AT&T Bell Laboratories, Microsoft, Microware, Trane Francks |
| Initial release | November 1973 |
| Written in | C |
| Operating system | Unix, Unix-like, V, Plan 9, Inferno, OS-9, MSX-DOS, FreeDOS, Windows, KolibriOS, IBM i |
| Platform | Cross-platform |
| Type | Command |
| License | coreutils: GPLv3+ FreeDOS: GPLv2 Plan 9: MIT License |
In computing, sleep is a command in Unix, Unix-like and other operating systems that suspends program execution for a specified time.
Overview
[edit]The sleep instruction suspends the calling process for at least the specified number of seconds (the default), minutes, hours or days.
sleep for Unix-like systems is part of the X/Open Portability Guide since issue 2 of 1987. It was inherited into the first version of POSIX and the Single Unix Specification.[1] It first appeared in Version 4 Unix.[2]
The version of sleep bundled in GNU coreutils was written by Jim Meyering and Paul Eggert.[3] The command is also available in the OS-9 shell,[4] in the KolibriOS Shell,[5] and part of the FreeDOS Package group Utilities.[6] The FreeDOS version was developed by Trane Francks and is licensed under the GPL.[7]
A sleep command is also part of ASCII's MSX-DOS2 Tools for MSX-DOS version 2.[8]
In PowerShell, sleep is a predefined command alias for the Start-Sleep cmdlet which serves the same purpose.[9] Microsoft also provides a sleep resource kit tool for Windows which can be used in batch files or the command prompt to pause the execution and wait for some time.[10] Another native version is the timeout command which is part of current versions of Windows.[11]
The command is available as a separate package for Microsoft Windows as part of the UnxUtils collection of native Win32 ports of common GNU Unix-like utilities.[12] The sleep command has also been ported to the IBM i operating system.[13]
Usage
[edit] sleep number
Where number is an integer[14] number to indicate the time period in seconds. Some implementations support floating point numbers.
Options
[edit]None.
Examples
[edit] sleep 30
Causes the current terminal session to wait 30 seconds.
sleep 18000
Causes the current terminal session to wait 5 hours
GNU sleep
[edit] sleep 3h ; mplayer foo.mp3
Wait 3 hours then play the file foo.mp3
Note that sleep 5h30m and sleep 5h 30m are illegal since sleep takes only one value and unit as argument. However, sleep 5.5h (a floating point[15]) is allowed. Consecutive executions of sleep can also be used.
sleep 5h; sleep 30m
Sleep 5 hours, then sleep another 30 minutes.
The GNU Project's implementation of sleep (part of coreutils) allows the user to pass an arbitrary floating point[15] or multiple arguments, therefore sleep 5h 30m (a space separating hours and minutes is needed) will work on any system which uses GNU sleep, including Linux.
Possible uses for sleep include scheduling tasks and delaying execution to allow a process to start, or waiting until a shared network connection most likely has few users to wget a large file.
See also
[edit]References
[edit]- ^ – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group
- ^ – FreeBSD General Commands Manual
- ^ "sleep(1): delay for specified amount of time - Linux man page". linux.die.net. Archived from the original on 2007-07-12. Retrieved 2019-02-28.
- ^ Paul S. Dayan (1992). The OS-9 Guru - 1 : The Facts. Galactic Industrial Limited. ISBN 0-9519228-0-7.
- ^ "Shell - KolibriOS wiki". wiki.kolibrios.org. Archived from the original on 2019-02-11. Retrieved 2019-03-25.
- ^ "ibiblio.org FreeDOS Group -- Utilities". www.ibiblio.org. Archived from the original on 2018-09-30. Retrieved 2018-11-16.
- ^ "ibiblio.org FreeDOS Package -- sleep (Unix-like)". www.ibiblio.org. Archived from the original on 2018-07-07. Retrieved 2018-08-10.
- ^ "MSX-DOS2 Tools User's Manual - MSX-DOS2 TOOLS ユーザーズマニュアル". April 1, 1993 – via Internet Archive.
- ^ "Start-Sleep (Microsoft.PowerShell.Utility) - PowerShell". docs.microsoft.com.
- ^ "Download Windows Server 2003 Resource Kit Tools from Official Microsoft Download Center". Microsoft. Archived from the original on 2019-06-11. Retrieved 2018-08-10.
- ^ "Timeout". docs.microsoft.com. Archived from the original on 2020-08-06. Retrieved 2020-09-13.
- ^ "Native Win32 ports of some GNU utilities". unxutils.sourceforge.net. Archived from the original on 2006-02-09. Retrieved 2025-08-11.
- ^ IBM. "IBM System i Version 7.2 Programming Qshell" (PDF). IBM. Archived (PDF) from the original on 2020-09-18. Retrieved 2020-09-05.
- ^ "sleep(3): sleep for specified number of seconds - Linux man page". linux.die.net. Archived from the original on 6 April 2019. Retrieved 19 April 2018.
- ^ a b "GNU Coreutils: sleep invocation". www.gnu.org. Retrieved 19 April 2018.
External links
[edit]- – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group
- – Plan 9 Programmer's Manual, Volume 1
- – Inferno General commands Manual
Sleep (command)
View on Grokipediasleep command is a standard utility in Unix-like operating systems that suspends the execution of a process for at least a specified interval, typically measured in seconds.[1] This command is essential for scripting and automation, allowing developers to introduce deliberate delays between operations, such as pacing repeated tasks or ensuring processes complete before proceeding.[1]
In its POSIX-compliant form, [sleep](/page/Sleep) accepts a single operand: a non-negative decimal integer representing the number of seconds to pause.[1] The command returns an exit status of 0 if the suspension completes successfully or is interrupted by a SIGALRM signal, and a non-zero status if an error occurs.[1] It supports no options in the base specification, emphasizing simplicity for portable shell scripts.[1]
Implementations like GNU coreutils extend this functionality for greater flexibility.[2] Here, sleep can handle floating-point numbers for sub-second precision and multiple arguments that sum their durations; optional suffixes—s for seconds, m for minutes, h for hours, and d for days—allow specifying longer intervals concisely.[2] Basic options include --help to display usage information and --version to output version details.[2] For instance, the synopsis is sleep NUMBER[SUFFIX]... or sleep OPTION.[2]
Common use cases include backgrounding delayed commands, such as (sleep 105; command) & to run a task after 105 seconds, or creating loops with periodic execution, like while true; do command; sleep 37; done to repeat every 37 seconds.[1] The command is part of the POSIX.1-2004 standard (IEEE Std 1003.1, 2004 Edition) and is included in core utilities packages across Linux distributions, AIX, and other systems.[1] As of GNU coreutils version 9.9 (November 2025), it is maintained under the GPLv3+ license by authors Jim Meyering and Paul Eggert.[3]
Description
Purpose and Functionality
The sleep command is a command-line utility in Unix-like operating systems that suspends the execution of the calling process, such as a shell script or the current shell, for a user-specified duration typically measured in seconds.[4] This suspension pauses the process without terminating it, allowing the operating system scheduler to allocate CPU time to other running processes during the interval.[4] Defined as part of the POSIX standard, it provides a portable mechanism for introducing controlled delays in command-line environments.[4] Common use cases for the sleep command include inserting timing delays in batch processing jobs to sequence operations, creating pauses between steps in automated scripts to ensure orderly execution or resource availability, and simulating time-dependent workloads during software testing.[5] For instance, it enables scripting scenarios where commands must wait for external events, such as network responses or file system updates, without consuming computational resources unnecessarily.[6] Upon normal completion of the specified duration, the sleep command returns an exit status of 0, indicating success.[4] If interrupted by a signal other than SIGALRM, such as SIGINT (generated by Ctrl+C) or SIGTERM, sleep exits with a non-zero status; in shells like Bash, this is typically reported as 128 plus the signal number—for example, 130 for SIGINT (signal 2) or 143 for SIGTERM (signal 15).[4][7] During the sleep period, the command has minimal impact on system resources, using negligible CPU cycles as it relies on kernel-level sleep mechanisms rather than active polling.[2]Syntax
Thesleep command follows the basic syntax sleep time, where time is a required operand consisting of a non-negative decimal integer specifying the number of seconds to suspend execution, with a maximum value of 2,147,483,647 in POSIX-compliant implementations.[4] This operand must be the first and only positional argument; additional arguments are not permitted under the POSIX standard.[4]
In extended implementations such as GNU Coreutils, the syntax is more flexible: sleep NUMBER[SUFFIX]..., where NUMBER is a non-negative floating-point value (supporting decimal fractions and scientific notation, e.g., 5.5 or 1.234e-2; a value of 0 results in no delay), and SUFFIX is optional and denotes the time unit—s for seconds (default if omitted), m for minutes, h for hours, or d for days.[8] Multiple such arguments may be provided, with their durations summed (e.g., sleep 1h 30m).[8] Fractional times are supported, such as 0.5s for half a second, and some implementations leverage system calls like nanosleep(2) to achieve precision down to nanoseconds, though actual resolution depends on the underlying hardware and kernel timers.[9]
If the provided operand is invalid—such as non-numeric input, negative values, or malformed suffixes—the command prints a diagnostic message to standard error (e.g., "sleep: invalid time interval 'foo'") and terminates with a non-zero exit status, typically 1.[8][4] In POSIX terms, any error in operand parsing results in an exit status greater than 0, without successful suspension.[4]
Arguments and Options
Time Specification
The time specification for the sleep command is provided as a non-negative number representing the duration, optionally followed by a unit suffix to indicate the time scale. In standard POSIX implementations, the operand is a decimal integer denoting seconds directly, with no suffixes supported. However, widely used variants like GNU coreutils extend this to allow flexible unit suffixes for convenience: 's' for seconds (the default, equivalent to a multiplier of 1), 'm' for minutes (multiplier of 60), 'h' for hours (multiplier of 3600), and 'd' for days (multiplier of 86400). GNU sleep also accepts multiple such specifications, which are summed to compute the total duration.[4][8] The specified duration is internally converted to total seconds using the formula: \text{total_seconds} = \text{NUMBER} \times \text{multiplier} where the multiplier corresponds to the unit (1 for seconds, 60 for minutes, 3600 for hours, or 86400 for days); if no suffix is provided, the multiplier is 1. For example,sleep 2m computes as 2 × 60 = 120 total seconds, suspending execution for two minutes. Similarly, sleep 1h equals 1 × 3600 = 3600 seconds (one hour), and sleep 3d equals 3 × 86400 = 259200 seconds (three days). This conversion enables users to specify delays in more intuitive units without manual arithmetic.[8]
A duration of zero, such as sleep 0, results in immediate exit with a success status of 0, as no suspension is required. Negative values are invalid and treated as errors, typically causing the command to fail with an appropriate diagnostic message and non-zero exit status, since only non-negative durations are permitted.[4][8]
GNU coreutils implementations support floating-point numbers for the duration operand, allowing sub-second precision (e.g., sleep 0.5 for half a second), which extends beyond strict POSIX integer requirements. However, the actual sleep resolution is constrained by the underlying system timer granularity, typically achieving about 1 millisecond accuracy on modern Unix-like systems due to mechanisms like nanosleep.[8]
There is no hard maximum duration defined in the POSIX standard beyond the operand being a non-negative integer up to 2,147,483,647 seconds (approximately 68 years), but practical limits in older systems arise from 32-bit integer overflow constraints when converting or storing the total seconds value.[4]
Command-Line Options
The core POSIX specification for thesleep command defines no command-line options, emphasizing an argument-only invocation where the utility operates solely on the provided time operand.[4] Implementations adhering strictly to POSIX, such as those in minimal Unix-like environments, thus support no flags, ensuring portability for basic usage without additional parameters.[4]
Common extensions in non-POSIX implementations introduce utility options for metadata and diagnostics, such as --help to display usage information and --version to output version details, both of which cause the command to exit immediately without suspending execution.[8] These long-form options are widely supported in GNU Coreutils and similar toolsets.[2] In practice, options must precede the time argument in the command line; any unknown or misplaced options trigger an error, typically resulting in a non-zero exit status such as 1.[8]
Successful invocation of --help or --version yields an exit code of 0, aligning with standard utility behavior for informational requests.[8] Conversely, invalid options or parsing errors lead to failure with a non-zero exit code, often 1, while the core suspension functionality—requiring no flags—remains portable across standards-compliant systems.[4] Variations in option support highlight the need for cautious scripting in heterogeneous environments, though the flagless form ensures universal compatibility.[8]
Usage
Basic Examples
Thesleep command is commonly used to introduce a simple delay in command-line operations, suspending execution for the specified duration without performing any other actions. In its basic form, it accepts a single argument representing the number of seconds to pause, as defined in the POSIX standard, where the argument must be a non-negative decimal integer up to 2,147,483,647 seconds.[4]
For instance, the following invocation pauses the shell for 5 seconds before returning control to the prompt:
sleep 5
sleep 5
sleep 0.5 pauses for half a second, while sleep 1m pauses for 1 minute (using 'm' for minutes).[8]
To chain commands with a delay, the [sleep](/page/Sleep) utility can be combined with shell operators like &&, ensuring the subsequent command executes only after the pause completes successfully. An example is:
sleep 3 && echo "Done"
sleep 3 && echo "Done"
sleep outputs an error message to standard error and exits with a non-zero status (typically 1). For example:
sleep abc
sleep abc
Script Integration
Thesleep command plays a crucial role in shell scripting by enabling precise timing control for automation tasks, such as pacing operations in loops or introducing pauses based on conditions. In POSIX-compliant shells, it suspends execution for the specified duration, allowing scripts to simulate timed behaviors without busy-waiting, which conserves system resources.[4] This integration facilitates reliable control flow in automated workflows, from simple delays to complex signal-aware routines.[8]
Within loops, sleep creates rhythmic iterations, ensuring commands execute at controlled intervals. For instance, the following Bash loop prints numbers with a one-second delay between each:
for i in {1..3}; do echo $i; sleep 1; done
for i in {1..3}; do echo $i; sleep 1; done
while loop, it can enforce repetition with timing:
i=1; while [ $i -le 3 ]; do echo $i; sleep 1; i=$((i+1)); done
i=1; while [ $i -le 3 ]; do echo $i; sleep 1; i=$((i+1)); done
sleep pauses execution only when specific branches are taken, enhancing script responsiveness. An example in a Bash if statement might delay a resource-intensive operation if a condition like file availability is unmet:
if [ ! -f /tmp/data.txt ]; then [sleep](/page/Sleep) 10; fi
if [ ! -f /tmp/data.txt ]; then [sleep](/page/Sleep) 10; fi
sleep runs asynchronously to allow parallel execution while coordinating via the wait builtin. For example:
sleep 5 &
wait
echo "Delay complete"
sleep 5 &
wait
echo "Delay complete"
& operator backgrounds the delay, freeing the script for other actions, and wait synchronizes completion.[11] This is particularly effective for timing independent subprocesses, such as staggered starts in parallel jobs.[8] POSIX specifies that backgrounded sleep behaves identically to foreground, suspending until the interval elapses or interrupted.[4]
Error handling in scripts often involves trapping signals during sleep to resume, log, or exit gracefully upon interruption. Bash's trap command captures signals like SIGINT, executing custom actions even mid-delay:
trap 'echo "Interrupted"; exit 1' SIGINT
[sleep](/page/Sleep) 30
trap 'echo "Interrupted"; exit 1' SIGINT
[sleep](/page/Sleep) 30
sleep may terminate early with exit status 0, allowing traps to manage timeouts in timing-sensitive scripts.[4] This ensures robust automation, such as cleaning up resources on external signals.[7]
A common pitfall arises in non-interactive shells, where sleep blocks the entire script until completion, potentially delaying cron jobs if not accounted for in design. For rate limiting in cron-scheduled scripts, sleep spaces operations to avoid API throttling, as in a loop fetching data with delays between requests.[8] However, since cron executes jobs in isolated non-interactive environments, a blocking sleep affects only that invocation, not concurrent processes.[4] To mitigate interruptions, combining traps with backgrounded sleep allows scripts to remain interruptible without halting flow.[7]
Implementations and Variants
POSIX Standard
Thesleep utility is standardized in the POSIX.1-2004 specification (IEEE Std 1003.1, 2004 Edition, Issue 6), where it is defined as a required command in the Shell and Utilities volume of the Base Definitions and Headers, as well as the System Interfaces and Utilities volumes.[13] This standardization ensures a baseline level of portability across conforming Unix-like systems, mandating that sleep suspend execution of the current shell process for at least the specified duration without introducing unnecessary variations.[13]
The required features of the POSIX sleep utility include support for a time operand specified as a non-negative decimal integer representing seconds, with seconds as the default unit.[13] No command-line options are mandated, and the utility accepts only a single positional argument for the time value.[13] Upon successful suspension or interruption by a SIGALRM signal, sleep shall exit with a status of 0; any error, such as an invalid time argument, results in an exit status greater than 0.[13] For conformance, implementations must handle time values up to at least 2147483647 seconds (2^31 - 1) without overflow, potentially by using multiple internal calls if the underlying operating system imposes lower limits on individual sleep durations.[13] The specification for sleep has remained unchanged in subsequent POSIX editions, including Issue 7 (2018).[4]
Strict POSIX conformance imposes limitations, such as the absence of support for time suffixes (e.g., 'm' for minutes, 'h' for hours, or 'd' for days), which are considered optional extensions in non-standard implementations.[13] This minimal specification promotes interoperability by avoiding dependencies on enhanced features, ensuring that portable scripts can rely solely on integer seconds for delays.[13]
GNU Coreutils Version
The GNU implementation of the sleep command forms part of the GNU Coreutils package, a collection of basic file, shell, and text utilities maintained by the Free Software Foundation since the package's initial release in 1992 as a merger of earlier GNU fileutils, sh-utils, and textutils projects. Widely adopted in Linux distributions and other GNU/Linux environments, this version provides enhanced functionality beyond the minimal POSIX requirements, emphasizing flexibility for scripting and system administration tasks. A key enhancement in the GNU version is its support for expressive time specifications, allowing multiple command-line arguments whose durations are summed, unit suffixes ('s' for seconds as default, 'm' for minutes, 'h' for hours, and 'd' for days), and floating-point values for fractional seconds, enabling sub-second precision limited only by the system's clock resolution—typically down to nanoseconds via the underlying nanosleep system call. For instance,sleep 1.5 or sleep 0.001s delays execution by 1.5 seconds or 1 millisecond, respectively, while sleep 2h 30m sums to 150 minutes; this contrasts with POSIX's restriction to a single integer seconds value without suffixes or decimals. Additionally, the GNU sleep accepts the special value "inf" to pause indefinitely, useful for process management or testing scenarios.[8]
The command includes standard GNU options such as --help to print usage details and --version to display the Coreutils version and copyright information. Regarding portability and reliability, the GNU implementation diverges from POSIX by treating fractional seconds and suffixes as essential features in Linux practice, while maintaining compatibility through integer-only usage; it leverages 64-bit arithmetic for handling large durations up to approximately 584 billion years without overflow. Updates in releases such as coreutils 9.5 (March 2024), which improved timing precision using a monotonic clock, and 9.7 (April 2025), which fixed under-sleeping issues in loops, have enhanced consistency; as of November 2025, the latest stable version is 9.9.[14][8]
Other Variants
Implementations in other Unix-like systems often extend the POSIX baseline similarly to GNU. For example, the FreeBSD version ofsleep supports multiple arguments, floating-point numbers, and suffixes for seconds, minutes, hours, and days, providing sub-second precision.[15] In resource-constrained environments, BusyBox offers a minimal sleep that adheres to POSIX but lacks advanced features like suffixes, suitable for embedded systems.[16]
History and Portability
Origins in Unix
Thesleep command was introduced in Version 4 AT&T UNIX, released in November 1973 by AT&T Bell Laboratories, as a standard utility in the early Unix shell environment.[17] This release provided shell scripting capabilities that benefited from reliable timing mechanisms like sleep for coordinating command execution in multi-user environments.
The original implementation was a straightforward C program that invoked the sleep() library function to suspend the process. This function, in turn, relied on the alarm() system call to schedule a SIGALRM signal after the specified interval and then paused execution using pause() until the signal arrived or was interrupted.[18] The command accepted a single integer argument representing seconds, with a limitation of up to 65,535 seconds due to the unsigned short data type used for the timer value. This design ensured efficient resource usage by yielding control to the scheduler rather than polling in a loop, which was critical in the resource-constrained PDP-11 systems of the era.
The primary purpose of sleep was to enable timed delays in shell scripts, facilitating tasks such as scheduling periodic commands or deferring actions in background processes without wasting CPU cycles on busy-waiting. For instance, early examples in the documentation illustrated its use for executing a command after a delay, like (sleep 105; command)&, or in loops for repetitive operations, such as while true; do command; sleep 37; done.[19] This addressed a key need in early Unix for non-blocking pauses that supported the growing complexity of automated scripting on shared systems.
Early documentation, including the Version 7 manual page, emphasized the seconds-only syntax and provided scripting examples to highlight its utility. By the time of 4.3BSD in 1986, the man page retained this basic description of suspending execution for an integer number of seconds, though fractional values were supported in some implementations.[20]
