0

I want to store yesterday's date in BASH variable to search for yesterday's files with that variable in the file-name wildcard search. I am using the following format for New York City, NY, USA (EST) time zone, and wanted to know whether it is guaranteed to fetch yesterday's date from the system date; else I can make further changes to the variable.

 yesterday=$(TZ=GMT+28 date +%Y%m%d)
 ...
  for file in $HOME_DIR/*$yesterday*.txt;
 ...

The text filename in HOME_DIR would be as follows: "ABC_20171011064612.txt"

update 1: Attempt for removing daylight savings related issues:

yesterday=$(echo -e "$(TZ=GMT+28 date +%Y%m%d)\n$(TZ=GMT+18 date +%Y%m%d)"|grep -v $(date +%Y%m%d)|sort|tail -1)

1) Convert two dates to string, 24 hours and 14 (picked arbitrarily to be less than 24 hours) hours before today's date

2) Filter for dates that are not today's date

3) Sort strings from 2) in ascending order

4) Assign yesterday variable to last tail -1 entry of the list

Parth Patel
  • 23
  • 1
  • 4
  • 1
    Maybe try **Perl**... `perl -MPOSIX -le '@now = localtime; $now[3]--; print scalar localtime mktime @now'` – Mark Setchell Oct 12 '17 at 20:07
  • Which version of bash? If you have 4.3, then you can use `printf %()T` to do date formatting using shell-builtin operations, so you can extract epoch time and then subtract. – Charles Duffy Oct 12 '17 at 20:22
  • `GNU bash, version 4.3.30(1)-release (powerpc-ibm-aix5.1.0.0)` – Parth Patel Oct 13 '17 at 20:26
  • How about https://stackoverflow.com/a/21283578/3220113 ? – Walter A Oct 15 '17 at 21:33
  • Greetings Walter A, Thank you, I will try out the AIX grep solution mentioned on that link to circumvent daylight savings issues. – Parth Patel Oct 16 '17 at 14:01
  • Using the above link, I was able to induce the following solution-attempt: `yesterday=$(echo -e "$(TZ=GMT+28 date +%Y%m%d)\n$(TZ=GMT+18 date +%Y%m%d)|grep -v $(date +%Y%m%d)|sort|tail -1)` – Parth Patel Oct 16 '17 at 20:29

2 Answers2

1

It may not be always right due to DST, although it will not be a big issue. You could rather say:

yesterday=$(date -d yesterday +%Y%m%d)
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • 1
    I get `date: not recognized flag d ` – Parth Patel Oct 13 '17 at 13:09
  • Sorry... I've just learned AIX date(1) does not accept -d option. Your first approach $(TZ=GMT+28 date +%Y%m%d) should properly work anyway except for around midnight. Modifying TZ is a commonly used workaround to calculate shifted time and day. – tshiono Oct 13 '17 at 14:08
0

You attempted

yesterday=$(echo -e "$(TZ=GMT+28 date +%Y%m%d)\n$(TZ=GMT+18 date +%Y%m%d)|
            grep -v $(date +%Y%m%d)|sort|tail -1)

I think it worked.

Walter A
  • 19,067
  • 2
  • 23
  • 43