Monday, January 31, 2022

[SOLVED] Create if non exist directories with year name and subdirectories having month and day date

Issue

I am moving logs from a server daily at midnight to a remote server. on the remote server i have to store these logs in relevant folders. means yesterday's logs should be in folder hierarchy like 2021->04->05

my script shall create any none-exist folder/sub folder, I wrote the below script but it create only the main folder (2021) and nothing for its child folder. I believe i have something wrong on the script

YEAR="$(date +"%Y")"
MONTH="$(date +"%m")"
DAY="$(date +"%d")"

if [ ! -d "$YEAR" ]; then
 
 mkdir $YEAR
   cd $YEAR
 if [ ! -d "$MONTH" ]; then
      mkdir $MONTH
      cd $MONTH
  if [ ! -d "$DAY" ]; then
        mkdir $DAY
  fi
   fi
fi

Solution

It's a good idea to indent your code consistently. It makes it easier to spot errors.

Your if statements do nothing when a test fails. You need to add code to handle the else cases:

if [ ! -d "$YEAR" ]; then
    mkdir $YEAR
    cd $YEAR
    if [ ! -d "$MONTH" ]; then
        mkdir $MONTH
        cd $MONTH
        if [ ! -d "$DAY" ]; then
            mkdir $DAY
        else
            : # do this if DAY directory exists
        fi
    else
        : # do this if MONTH directory exists
    fi
else
    : # do this if YEAR directory exists
fi

Alternatively, in this case it is cleaner to unroll into separate tests:

if [ ! -d "$YEAR" ]; then
    mkdir $YEAR
fi
cd $YEAR
if [ ! -d "$MONTH" ]; then
    mkdir $MONTH
fi
cd $MONTH
if [ ! -d "$DAY" ]; then
    mkdir $DAY
fi
cd ../..

However, it is even simpler to just let mkdir do the work for you with the -p option which creates any directories that are needed:

mkdir -p "$YEAR/$MONTH/$DAY"

# or: mkdir -p "$(date +%Y/%m/%d)"


Answered By - jhnc
Answer Checked By - Mary Flores (WPSolving Volunteer)