I am wanting to know is it possible to have sleep in a bash script have a variable time that is read from a file? I am wanting to perform operations in the script that vary in length that will have the timings set by another script.

  • Yes. It is possible. Do you want to know how to pass a value from a file to the sleep command as a parameter or how to pass a value generated by another command as a parameter?
    – jfs
    Feb 18 '15 at 10:33
  • Long story short I am wanting to turn a gpio pin on, then wait for a specific time that is recorded in a file, then turn the pin off. Another script will be setting the wait time, and this will need to read it.
    – user3001
    Feb 18 '15 at 19:25
  • do you want to wait for a specific (absolute) time such as 2015-02-20 12:00:00+00:00 or do you want to wait given number of seconds e.g., 10 (sleep 10 seconds). What do you want to happen if your computer hibernates: do you want the script to wake up immediately or wait the rest of the time e.g., 3 seconds?
    – jfs
    Feb 19 '15 at 4:30
  • Dedicated server sending commands to raspberry pi over ssh, wont be any hibernation. It will be a given number of seconds, but will change daily, hence the need to read from file to get correct wait time
    – user3001
    Feb 19 '15 at 6:20

To sleep the number of seconds specified in timeout.txt file:

read timeout <timeout.txt
sleep $timeout

Or using bash-specific syntax:

sleep $(<timeout.txt)

Generally this is just a question of getting the information into your script, not so much about the sleep command.

Lets make a simple script 'sleepytime' to get the information from a file (I assume there is just one integer value in that file):


sleep_time_X=$(cat "X.sleepytime")
sleep_time_Y=$(cat "Y.sleepytime")

echo "Going to sleep $sleep_time_X second(s)"
sleep $sleep_time_X
echo "Going to sleep $sleep_time_Y second(s)"
sleep $sleep_time_Y

then on the command prompt:

$ touch Y.sleepytime
$ touch X.sleepytime
$ echo "1" > X.sleepytime 
$ echo "2" > Y.sleepytime
$ ./sleepytime
Going to sleep 1 second(s)
Going to sleep 2 second(s)

But it seems that is not a generally applicable approach. The sleep time might depend on factors outside of our control (e.g network requests, downloads etc). Then it would be preferable to wait until the job is done. This can be accomplished with the wait command. Let's make an additional script that calls our sleep script from above:


# Call the sleep script and send it to background (with '&')
./sleepytime &

echo "Waiting for sleepyhead"

The output is:

Waiting for sleepyhead
Going to sleep 1 second(s)
Going to sleep 2 second(s)

Note that the output of the first script comes after "Waiting for ...". Maybe that is an option for you...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.