cron can be used to schedule running a program once in a while. But it seems to be not specific to an existing shell process.

If I have a script which accesses the state of a specific bash process (e.g. to access the output of running jobs and dirs in the shell by source the script), how can I schedule its running in the specific bash process once in a while?


update: neither reply actually can directly access the state of an existing bash process. They can indirectly for some state information copied from the parent shell process to the child shell process. I don't remember why I accepted one.


Not entirely sure what you're after, but you can kick off a background job that does something and then waits X seconds, before repeating.


( while : ; do echo hello ; sleep 10 ; done ) &
  • Thanks. Will it be possible to run a command in a shell at a specific time every week, day, or hour? – Tim Jul 26 '18 at 21:08
  • Thanks. Can unix.stackexchange.com/a/458957/674 do more than your solution? – Tim Jul 29 '18 at 4:39

You could make use of the date command to dynamically adjust the duration of the sleep operation.


now() { date '+%s'; }
next() { date -d $(date -d "1 hours" '+%H:00:00') '+%s'; }

( while : ; do echo "Your Tasks Here" ; sleep $(next) - $(now) ; done ) $ 

The next() function inner date format is structured to run on the hour. If you wanted it to run every fifteen minutes you could adjust as follows.

next() { date -d $(date -d "15 minutes" '+%H:%M:00') '+%s'; }

See also: Linux date command, finding seconds to next hour

Note: Killing the above script is a bit annoying due to the sleep operation happening in the background. Kill by PID or consider not back-grounding the loop operation.

  • Thanks. What can your solution do which steve's can't? – Tim Jul 27 '18 at 22:13
  • date -d $(date -d "1 hours" '%H:00:00) '+%s'; has some error. – Tim Jul 29 '18 at 0:20
  • Why two functions? You could combine them into one: time() { local now=$(date '+%s'); local next=$(date -d "$*" '+%s'); echo "$((next-now))"; }. This could be called like sleep "$(time 1 hours)". – Jesse_b Jul 29 '18 at 12:56
  • Additionally with GNU sleep this becomes overkill as GNU sleep can take arguments like: sleep 1h or sleep 15m – Jesse_b Jul 29 '18 at 12:56
  • Good points. The the command I posted could help if the command should run relative to a specific time of day, as if it was scheduled via cron, but that scheduling is managed within the BASH script itself. Regarding GNU sleep, that's probably the best way to do it if you just need regular interval and don't care when it occurs within the hour. – curtlezumi Aug 7 '18 at 15:43

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.