Hubbry Logo
Sleep (command)Sleep (command)Main
Open search
Sleep (command)
Community hub
Sleep (command)
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Contribute something
Sleep (command)
Sleep (command)
from Wikipedia
sleep
DevelopersAT&T Bell Laboratories, Microsoft, Microware, Trane Francks
Initial releaseNovember 1973; 52 years ago (1973-11)
Written inC
Operating systemUnix, Unix-like, V, Plan 9, Inferno, OS-9, MSX-DOS, FreeDOS, Windows, KolibriOS, IBM i
PlatformCross-platform
TypeCommand
Licensecoreutils: 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]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The sleep command is a standard utility in operating systems that suspends the execution of a process for at least a specified interval, typically measured in seconds. 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. In its POSIX-compliant form, [sleep](/page/Sleep) accepts a single : a non-negative representing the number of seconds to pause. The command returns an of 0 if the suspension completes successfully or is interrupted by a SIGALRM signal, and a non-zero status if an error occurs. It supports no options in the base specification, emphasizing simplicity for portable shell scripts. Implementations like coreutils extend this functionality for greater flexibility. 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. Basic options include --help to display usage information and --version to output version details. For instance, the synopsis is sleep NUMBER[SUFFIX]... or sleep OPTION. 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. The command is part of the POSIX.1-2004 standard (IEEE Std 1003.1, 2004 Edition) and is included in core utilities packages across distributions, AIX, and other systems. As of coreutils version 9.9 (November 2025), it is maintained under the GPLv3+ license by authors Jim Meyering and Paul Eggert.

Description

Purpose and Functionality

The sleep command is a command-line utility in 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. This suspension pauses the process without terminating it, allowing the operating system scheduler to allocate to other running processes during the interval. Defined as part of the standard, it provides a portable mechanism for introducing controlled delays in command-line environments. Common use cases for the sleep command include inserting timing delays in jobs to sequence operations, creating pauses between steps in automated scripts to ensure orderly execution or resource availability, and simulating time-dependent workloads during . For instance, it enables scripting scenarios where commands must wait for external events, such as network responses or updates, without consuming computational resources unnecessarily. Upon normal completion of the specified duration, the sleep command returns an of 0, indicating . 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). 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.

Syntax

The sleep command follows the basic syntax sleep time, where time is a required consisting of a non-negative specifying the number of seconds to suspend execution, with a maximum value of 2,147,483,647 in -compliant implementations. This must be the first and only positional ; additional arguments are not permitted under the standard. In extended implementations such as Coreutils, the syntax is more flexible: sleep NUMBER[SUFFIX]..., where NUMBER is a non-negative floating-point value (supporting decimal fractions and , 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. Multiple such arguments may be provided, with their durations summed (e.g., sleep 1h 30m). 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. If the provided is —such as non-numeric input, negative values, or malformed suffixes—the command prints a diagnostic message to (e.g., "sleep: invalid time interval 'foo'") and terminates with a non-zero , typically 1. In terms, any error in operand parsing results in an greater than 0, without successful suspension.

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 implementations, the operand is a denoting seconds directly, with no suffixes supported. However, widely used variants like 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). sleep also accepts multiple such specifications, which are summed to compute the total duration. 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. 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 , since only non-negative durations are permitted. 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 integer requirements. However, the actual sleep resolution is constrained by the underlying system timer granularity, typically achieving about 1 accuracy on modern systems due to mechanisms like nanosleep. There is no hard maximum duration defined in the standard beyond the operand being a non-negative up to 2,147,483,647 seconds (approximately 68 years), but practical limits in older systems arise from 32-bit constraints when converting or storing the total seconds value.

Command-Line Options

The core specification for the sleep command defines no command-line options, emphasizing an argument-only invocation where the utility operates solely on the provided time . Implementations adhering strictly to , such as those in minimal environments, thus support no flags, ensuring portability for basic usage without additional parameters. 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. These long-form options are widely supported in Coreutils and similar toolsets. 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 such as 1. Successful invocation of --help or --version yields an exit code of 0, aligning with standard utility behavior for informational requests. 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. Variations in option support highlight the need for cautious scripting in heterogeneous environments, though the flagless form ensures universal compatibility.

Usage

Basic Examples

The sleep 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 standard, where the argument must be a non-negative decimal integer up to 2,147,483,647 seconds. For instance, the following invocation pauses the shell for 5 seconds before returning control to the prompt:

sleep 5

sleep 5

This is useful for timing sequences or throttling operations in interactive sessions. Many implementations, such as the GNU Coreutils version, extend this functionality to support fractional seconds and time unit suffixes for greater flexibility in specifying durations. For example, sleep 0.5 pauses for half a second, while sleep 1m pauses for 1 minute (using 'm' for minutes). 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"

This delays output by 3 seconds before printing "Done" to the console. If an invalid argument is provided, such as a non-numeric value, sleep outputs an error message to standard error and exits with a non-zero status (typically 1). For example:

sleep abc

sleep abc

This results in an error like "sleep: invalid number 'abc'" and immediate termination.

Script Integration

The sleep 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. This integration facilitates reliable control flow in automated workflows, from simple delays to complex signal-aware routines. 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

This pattern is common for tasks like monitoring or periodic , where the delay prevents overwhelming the . Similarly, in a 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

Such constructs are portable across POSIX environments, supporting up to approximately 68 years of delay in a single invocation. For conditional delays, 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

Here, the script waits 10 seconds before proceeding, useful for polling in without constant checks. This approach integrates seamlessly with shell logic, avoiding premature failures in dependent tasks. In background processes, 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"

The & operator backgrounds the delay, freeing the script for other actions, and wait synchronizes completion. This is particularly effective for timing independent subprocesses, such as staggered starts in parallel jobs. POSIX specifies that backgrounded sleep behaves identically to foreground, suspending until the interval elapses or interrupted. 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

If Ctrl+C (SIGINT) arrives, the trap fires immediately after the signal handler, preventing abrupt termination. For SIGALRM, POSIX may terminate early with 0, allowing traps to manage timeouts in timing-sensitive scripts. This ensures robust , such as cleaning up resources on external signals. A common pitfall arises in non-interactive shells, where blocks the entire script until completion, potentially delaying jobs if not accounted for in design. For in cron-scheduled scripts, spaces operations to avoid throttling, as in a loop fetching data with delays between requests. However, since cron executes jobs in isolated non-interactive environments, a blocking affects only that , not concurrent processes. To mitigate interruptions, combining traps with backgrounded allows scripts to remain interruptible without halting flow.

Implementations and Variants

POSIX Standard

The sleep utility is standardized in the .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. This standardization ensures a baseline level of portability across conforming systems, mandating that sleep suspend execution of the current shell for at least the specified duration without introducing unnecessary variations. The required features of the sleep utility include support for a time specified as a non-negative representing seconds, with seconds as the default unit. No command-line options are mandated, and the utility accepts only a single positional argument for the time value. 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 greater than 0. For conformance, implementations must handle time values up to at least seconds (2^31 - 1) without overflow, potentially by using multiple internal calls if the underlying operating system imposes lower limits on individual sleep durations. The specification for sleep has remained unchanged in subsequent editions, including Issue 7 (). 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. This minimal specification promotes interoperability by avoiding dependencies on enhanced features, ensuring that portable scripts can rely solely on integer seconds for delays.

GNU Coreutils Version

The GNU implementation of the sleep command forms part of the Coreutils package, a collection of basic file, shell, and text utilities maintained by the since the package's initial release in 1992 as a merger of earlier fileutils, sh-utils, and textutils projects. Widely adopted in distributions and other /Linux environments, this version provides enhanced functionality beyond the minimal 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 . For instance, sleep 1.5 or sleep 0.001s delays execution by 1.5 seconds or 1 , 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. 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 ( 2025), which fixed under-sleeping issues in loops, have enhanced consistency; as of November 2025, the latest stable version is 9.9.

Other Variants

Implementations in other systems often extend the baseline similarly to . For example, the version of sleep supports multiple arguments, floating-point numbers, and suffixes for seconds, minutes, hours, and days, providing sub-second precision. In resource-constrained environments, offers a minimal sleep that adheres to but lacks advanced features like suffixes, suitable for embedded systems.

History and Portability

Origins in Unix

The sleep command was introduced in Version 4 UNIX, released in November 1973 by Bell Laboratories, as a standard utility in the early environment. This release provided shell scripting capabilities that benefited from reliable timing mechanisms like sleep for coordinating command execution in multi-user environments. The original was a straightforward program that invoked the sleep() function to suspend the process. This function, in turn, relied on the alarm() to schedule a SIGALRM signal after the specified interval and then paused execution using pause() until the signal arrived or was interrupted. The command accepted a single integer argument representing seconds, with a limitation of up to 65,535 seconds due to the unsigned short used for the 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 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 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. 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.

Standardization and Evolution

The sleep utility was first standardized as part of .1-1988 (IEEE Std 1003.1-1988), which defined its core behavior for suspending execution for an integral number of seconds in portable environments. This initial specification established sleep as a required utility in the shell and utilities volume, ensuring consistent syntax and semantics across compliant systems, with the operand specifying seconds and an of zero on successful completion or non-zero if interrupted. Subsequent refinements appeared in POSIX.1-2001, which aligned with the (SUS) and introduced enhancements for time-related functions, including support for finer-grained delays through related interfaces like nanosleep, though the sleep utility itself retained its integer-second limitation. The SUSv2 (1997), corresponding to X/Open Issue 5, clarified error handling for sleep, allowing an of zero in cases like SIGALRM interruption, improving predictability in scripted environments. POSIX.1-2008 made no substantive changes to sleep but reinforced portability requirements, emphasizing thread-safety and signal interactions to support modern multitasking systems. The specification evolved further through the Open Group Base Specifications, with Issue 6 (2004) and Issue 7 (2008) incorporating sleep into the broader framework, promoting cross-platform adoption. This influenced implementations on non-native systems, such as Windows via emulation layers like , which provides a compliant sleep utility for Unix scripting portability, and GNUWin32, an older porting project for core tools including sleep. On macOS, derived from BSD Unix, sleep adheres to these standards natively, ensuring compatibility with -compliant scripts. As of 2025, no major updates have altered the core definition of sleep, though alignment with XPG7 (X/Open Portability Guide Issue 7, equivalent to Base Specifications Issue 7) emphasized internationalization aspects, such as locale handling via environment variables like LANG, ensuring numeric remains locale-independent for global portability. Portability challenges persist on non- systems; for instance, original lacked a native sleep command, requiring emulations or workarounds like timed loops until later extensions in provided a compliant version. In modern containerized environments like Docker, standardization is achieved through lightweight implementations such as in , which offers a -compliant sleep utility supporting integer seconds and fractional extensions for embedded and minimalistic deployments.
Add your contribution
Related Hubs
Contribute something
User Avatar
No comments yet.