sleep - Linux


Overview

The sleep command in Linux is used to pause the execution of a script or a command for a specified period of time. This command is primarily useful in shell scripts or when executing a batch of commands sequentially, allowing time-dependent processes to complete or delays to be introduced.

Syntax

The basic syntax of the sleep command is:

sleep NUMBER[SUFFIX]
  • NUMBER can be an integer or floating-point number.
  • SUFFIX is an optional specifier for time units. If no suffix is used, the default is seconds (s). Available suffixes include:
    • s for seconds
    • m for minutes
    • h for hours
    • d for days

Multiple arguments can be used together to specify complex times. For example, sleep 2h 30m would pause for 2 hours and 30 minutes.

Options/Flags

The sleep command has very few options:

  • --help: Display a help message and exit.
  • --version: Output version information and exit.

Examples

  1. Basic Sleeping
    Pause a script for 10 seconds:

    sleep 10
    
  2. Multiple Time Periods
    Pause for 2 minutes and 15 seconds:

    sleep 2m 15s
    
  3. Floating-Point Numbers
    Pause for 1.5 seconds:

    sleep 1.5
    
  4. Script Delays
    Using sleep in a bash script to delay loops:

    for i in {1..5}; do
        echo "Iteration $i"
        sleep 1s
    done
    

Common Issues

  • Non-numeric Arguments: If non-numeric characters are included without a proper suffix, sleep will throw an error. Always specify time with correct numbers and suffixes.
  • Long Sleep Intervals: Using very long sleep intervals might make it seem like the script is stuck.

Integration

The sleep command can be integrated with other Linux commands to manage timing effectively:

#!/bin/bash
echo "Waiting for database to start."
sleep 10s
echo "Checking database status."
# Place a command here to check database status.

Combine sleep with loops for repeated checks:

#!/bin/bash
until ping -c 1 example.com; do
    echo "Waiting for 'example.com' to respond..."
    sleep 5s
done
  • wait: Waits for a process to change state.
  • timeout: Runs a command with a time limit.

For further reading and more detailed information, visit the official Linux man pages online.