superfluousAM superfluousAM - 2 months ago 10
Linux Question

Verifying directory path for conditional check (bash)

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?

Answer

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