Get yesterday's date in bash on Linux, DST-safe

ID : 20099

viewed : 20

Tags : linuxbashlinux

Top 5 Answer for Get yesterday's date in bash on Linux, DST-safe

vote vote

92

I think this should work, irrespective of how often and when you run it ...

date -d "yesterday 13:00" '+%Y-%m-%d' 
vote vote

88

Under Mac OSX date works slightly different:

For yesterday

date -v-1d +%F 

For Last week

date -v-1w +%F 
vote vote

78

This should also work, but perhaps it is too much:

date -d @$(( $(date +"%s") - 86400)) +"%Y-%m-%d" 
vote vote

69

If you are certain that the script runs in the first hours of the day, you can simply do

  date -d "12 hours ago" '+%Y-%m-%d' 

BTW, if the script runs daily at 00:35 (via crontab?) you should ask yourself what will happen if a DST change falls in that hour; the script could not run, or run twice in some cases. Modern implementations of cron are quite clever in this regard, though.

vote vote

59

Here a solution that will work with Solaris and AIX as well.

Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1 

The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

echo "$(TZ=GMT+30 date +%Y-%m-%d) $(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1 

Top 3 video Explaining Get yesterday's date in bash on Linux, DST-safe

Related QUESTION?