1

Right now, I have a script which creates a new directory each day by using the following naming scheme:

cur_date=$(date +"%m_%d_%y)
mkdir test_dir_$cur_date/

Which results in:

test_dir_09_12_16
test_dir_09_13_16
test_dir_09_14_16
etc...

as each day goes by.

What I'm trying to do is have a conditional check to see if the previous day directory exists and if it does, use rsync to transfer the differences from the previous day to the new day directory. My issue is that I'm now sure how to execute the conditional to do so. I know

if [ -d test_dir_%m_%d-1_%y]

probably isn't the right syntax so I'm hoping something along the lines of:

if [ -d test_dir_(previous_day)]; then
   rsync -av test_dir_(previous_day) test_dir_$cur_date/
fi

will work and not cause any errors. Is that possible?

superfluousAM
  • 111
  • 2
  • 13

2 Answers2

1

You can get previous day using:

pd=$(date -d '-1 day' '+%m_%d_%y')

then check for existance of directory use:

if [[ -d test_dir_${pd} ]]; then
   echo "exists"
   rsync -av "test_dir_${pd}" "test_dir_${cur_date}"
else
   echo "doesn't exist"
fi
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for the help! I didn't realize you could manipulate the output from `date` like that, guess I should have done more reading. However, instead of doing `date -d '-1 day'` like you said, I used @tripleee method below for getting yesterday's date which seems a little simpler. – superfluousAM Sep 12 '16 at 18:17
  • 1
    yes `date -d yesterday` is good enough for previous day but using `-1 day` or `-2 day` etc allows you to get today-1, today-2, today-3 easily. – anubhava Sep 12 '16 at 18:53
  • Makes sense, thanks for the clarification! – superfluousAM Sep 12 '16 at 19:48
1

The shell doesn't know anything about date arithmetic. You will need to invoke date a second time to get yesterday's date. There is no straightforward way to get yesterday's date by pure arithmetic or string manipulation in the general case (think New Year's Day or March 1st).

On Linux (GNU coreutils) systems, date -d yesterday does this. On *BSD (including OSX), the syntax will be slightly different. If you portably need to work on both, write a wrapper, or use a scripting language.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Awesome, the method above I marked as the correct answer due to the syntax, however I used your method of `date -d yesterday` because it is much simpler to check for the previous date. Also, any way to get rid of the preceding `0` within the date format? Something like `9_12_16` instead of `09_12_16`? If not no worries, just wondering. – superfluousAM Sep 12 '16 at 18:18
  • Easily. See the manual. But again, using machine-readable date formats will simplify your life. – tripleee Sep 13 '16 at 03:16