What issue exists when multiple lines of ‘date’ are used in bash?

Posted on

Problem :

I’m currently reading through a book on bash programming, Pro Bash Programming. At one chapter (Chapter 4) they ask what problem the following script has. I myself have no clue after reading through. I must be missing something here. Can anyone show me what the issue here is?

year=$( date +%Y )
month=$( date +%m )
day=$( date +%d )
hour=$( date +%H )
minute=$( date +%M )
second=$( date +%S )

Solution :

What if you’re running these commands on Dec 31 at 23:59:59, and the clock ticks to the next second after, say, you get the month?

Safer:

read year month day hour minute second < <( date "+%Y %m %d %H %M %S" )

Be careful if you’re using those value to do arithmetic: the shell considers 08 and 09 to be invalid octal numbers, not valid decimal numbers.

I don’t this there is a real error in the script. But it is quite possible that, when reading all the string separately, you finally read a
‘second’ value which does not correspond to the ‘minute’ before that, because it already changed…

One thing I noticed is that it unsafely assumes all 6 calls to date are going to execute on the same wall-clock second. Imagine what might happen if the script gets to the first line around 2015-12-31 23:59:59.999 (plus or minus a few microseconds)?

I happen to know this book. Read on to chapter 9 and you will find a section on setting multiple variables from a single command. There they will give an explanation, what’s going on here.

In a gist it’s a) inefficient (calling date is rather expensive), and b) risky, for the reasons given by jcoppens.

Leave a Reply

Your email address will not be published.