7

I'm writing a bash script that should run on OSX and Ubuntu. I'm not sure if this particular problem is due to an OS mismatch; more likely it's a difference in the date command on the two shells, even though it's bash on both? Let's see.

On OSX's bash shell, in order to print a date from two days ago we're doing this:

date -v-2d +"%Y"."%m"."%d"

That -v flag is invalid on the Ubuntu bash shell however. Instead, there we're using:

date --date="2 days ago" +"%Y"."%m"."%d"

Unforuntately, the --date flag is unrecognized on our OSX bash shell.

I'd love for one command with flags that work in both instances, would anyone know what I could try?

  • This has nothing to do with bash. It's a problem with different implementations of date. – Cyrus Oct 16 '14 at 22:37
14

date is not a bash builtin. It is a system utility and that is something on which OSX and Linux differ. OSX uses BSD tools while Linux uses GNU tools. They are similar but not the same.

As you have found, on OSX, the -d flag to date controls daylight savings time whereas on Linux, it sets the display time. On OSX, -v adjusts the display date but, on Linux, the -v flag is an invalid option.

For the most part, both BSD and GNU strive for compatibility with the POSIX standard. If you check the POSIX standard for date, though, you will see that it is no help in this case: it does not support any syntax for adjusting the date.

If you want your code to work on both platforms, try:

[ "$(uname)" = Linux ] && date --date="2 days ago" +"%Y"."%m"."%d" || date -v-2d +"%Y"."%m"."%d"

Or (requires bash):

[ "$OSTYPE" = linux-gnu ] && date --date="2 days ago" +"%Y"."%m"."%d" || date -v-2d +"%Y"."%m"."%d"
-1

With ksh93 (which is IMHO much better than bash for scripting) you could use the printf builtin, e.g.:

printf '%(%Y.%m.%d)T' '2 days ago'

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.