Are there any substitutes, alternatives or bash tricks for delaying commands without using
sleep? For example, performing the below command without actually using sleep:
$ sleep 10 && echo "This is a test"
You have alternatives to
sleep: They are
cron. Contrary to
sleep these need you to provide the time at which you need them to run.
Make sure the
atd service is running by executing
service atd status.
Now let's say the date is 11:17 am UTC; if you need to execute a command at 11:25 UTC, the syntax is:
echo "This is a test" | at 11:25.
Now keep in mind that
atd by default will not be logging the completion of the jobs. For more refer this link. It's better that your application has its own logging.
You can schedule jobs in
cron, for more refer :
man cron to see its options or
crontab -e to add new jobs.
/var/log/cron can be checked for the info on execution on jobs.
sleep system call suspends the current execution and schedules it w.r.t. the argument passed to it.
As @Gaius mentioned , you can also add minutes time to
at command.But lets say time is
12:30:30 and now you ran the scheduler with
now +1 minutes. Even though 1 minute, which translates to 60 seconds was specified , the
at doesn't really wait till
12:31:30 to execute the job, rather it executes the job at
12:31:00. The time-units can be
minutes, hours, days, or weeks. For more refer
echo "ls" | at now +1 minutes
bash builtins, you can do:
coproc read -t 10 && wait "$!" || true
To sleep for 10 seconds without using
coproc is to make so that
read's stdin is a pipe where nothing will ever come out from.
|| true is because
wait's exit status will reflect a SIGALRM delivery which would cause the shell to exit if the
errexit option is set.
In other shells:
sleep built-in, no point in using anything else there (though they both also support
zsh also supports
read -t, but also has a builtin wrapper around
select(), so you can also use:
zmodload zsh/zselect zselect -t 1000 # centiseconds
If what you want is schedule things to be run from an interactive shell session, see also the
zsh/sched module in
Back in the days of microcomputers running BASIC, delays were usually accomplished with an empty loop:
FOR I = 1 TO 10000:NEXT
The same principle could be used to insert a delay in a shell script:
COUNTER=0; while [ $COUNTER -lt 10000 ]; do :; let COUNTER=COUNTER+1; done
Of course, the problem with this approach is that the length of the delay will vary from machine to machine according to its processor speed (or even on the same machine under different loads). Unlike
sleep, it will probably also max out your CPU (or one of its cores).
There is no built-in, that does the same as
sleep is built-in). However there are some other commands that will wait.
A few include.
cron: used to schedule tasks at a specific time.
inotifywait: used to wait for a file, or files to be modified/removed/added/etc