Solving a problem I had with the Unix date command in the right way
I have a personal shell script that for reasons beyond the scope
of this entry uses the Unix
date command to determine the current
day, month, and year. Recently I noticed that the shell script was
sometimes not working right on our Ubuntu 20.04 and 22.04 servers,
but was working right on 18.04, and tracked it down to the fact
that doing '
ssh server date' produced output in a different format
on 18.04 than on the other two.
; ssh server1804 date Sat May 7 20:56:00 EDT 2022 ; ssh server2204 date Sat May 7 08:56:00 PM EDT 2022
If I actually logged in to a 20.04 or 22.04 system and set up my normal
date output reverted to the 18.04 traditional Unix
format. Obviously this is some Unix (Linux) locale fun and games.
My first instinct was to spend time figuring out what magic environment
variable or system setting was different between the machines, so I
could get the
date format to come out right, so my script could
parse it properly again. Then I metaphorically bopped myself on the
forehead, because why was I even parsing the default output of
at all. Date has supported specifying the output format for a long time,
so if what I wanted was the day, the month, and the year, I should just
change the script to have date output only and exactly that:
dout="$(date +'%e %b %Y')"
Figuring out what's wrong with locales (or anything else) can be fun and interesting, but sometimes the right answer is to go around the problem entirely. I probably should remember and apply this more often than I do.
(Of course I could go one step further to just run
times, once for each of the day, the month, and the year. But I
reflexively twitch at things like that, even if it will never matter
for this particular personal script.)
PS: The hard to believe reason that this script didn't use a date format
from the start is that it's old enough to predate versions of
that supported this. It actually hasn't changed all that much from the
oldest-dated version I could easily find in my collection of stuff.