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.
2 Answers
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
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...
sleep
command as a parameter or how to pass a value generated by another command as a parameter?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?