Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • In Bash, you can use $SECONDS to count time intervals. I think it's the number of seconds since the shell started, not that it matters when taking a difference. Commented Feb 22, 2018 at 14:13
  • @ilkkachu, or read -t or $TMOUT. $SECONDS is broken in bash and mksh. time bash -c 'while ((SECONDS < 3)); do :; done' will last in between 2 and 3 seconds. Better to use zsh or ksh93 instead here (with typeset -F SECONDS) Commented Feb 22, 2018 at 14:16
  • @StéphaneChazelas, I don't think it's any different than using date +%s. Both give the time in full seconds, which does have the effect that the interval from, say, 1.9 to 4.0 looks like 3 full seconds, even though it's really 2.1. It's hard to work around that if all you can't access the fractional seconds. But yes, they should probably sleep here instead of busylooping, and then read -t could just as well be used. Even if you do sleep manually, time bash -c 'while [[ $SECONDS -lt 3 ]]; do sleep 1; done' works just fine. Commented Feb 22, 2018 at 14:31
  • 1
    ksh93 and zsh are OK with that (zsh used not to). Even with integer $SECONDS, setting SECONDS=0 ensures that $SECONDS will reach 1 in exactly 1 second. That's not the case with bash as it uses time() to track $SECONDS instead of gettimeofday(). I reported bugs to mksh, zsh and bash some time ago, only zsh was fixed. (good point about the issue being the same with date +%s). Note that it's not a busyloop here, as we're reading from the output of tail -f over a pipe. Commented Feb 22, 2018 at 14:48
  • +1 and Bash has a "shortcut" using the built-in printf to emulate date without external tools or command substitution: printf -v t '%(%s)T' -1. Commented Feb 22, 2018 at 20:43