1

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.

4
  • 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, 2015 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, 2015 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, 2015 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, 2015 at 6:20

2 Answers 2

2

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

#!/bin/sh
read timeout <timeout.txt
date
sleep $timeout
date

Or using bash-specific syntax:

#!/bin/bash
date
sleep $(<timeout.txt)
date
1

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):

#!/bin/bash

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:

#!/bin/bash

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

echo "Waiting for sleepyhead"
wait

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...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .