date command, going back one or two days. Seeing different flags

33,829

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"
Share:
33,829

Related videos on Youtube

jkj2000
Author by

jkj2000

Updated on September 18, 2022

Comments

  • jkj2000
    jkj2000 over 1 year

    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?

    • minorcaseDev
      minorcaseDev over 9 years
      This has nothing to do with bash. It's a problem with different implementations of date.