• Uncategorized

About linux : Running-commands-in-a-loop-without-spawning-a-new-subshell-each-time

Question Detail

I have a bash script that reads in lots of dates in epoch time, and determines the (local) hour of the day at which they occurred. Relevant snippet:

while read ts
do
  hour="$(date -d@$((${ts} / 1000)) +%H)"
  ((hourly_counts["${hour}"]+=1))
done < "${jqfile}"

It’s rather slow, because it spawns a new subshell for each invocation of date. Is there a sensible way round this? It looks as though date doesn’t support multiple queries.

All I can think of is to spawn a new shell, and pipe date commands to it and get the results back, so that they all execute in the same shell. But I’m not clear on how to do this, and it seems a little over-engineered.

Question Answer

Use printf:

printf -v hour '%(%H)T' "$(( ts / 1000 ))"

Type help printf to know more about the command.

Also check strftime(3). Behavior may depend on the value of TZ and LC_TIME.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.