Rahul sawant
Rahul sawant

Reputation: 425

How do i create date specific folders in linux

I am naive in linux and looking for a guidance in one of the scripts I am developing

I have a path:

/data/mm/ms

I want to generate a script to create date specific folder for each day inside the above path. Here is what I have created but is incomplete

dir= dd/mm/ms                       //Existing directory
DIR_DATE=$(`date +%Y%m%d`)          //todays date stored inside a variable   
CREATE_DIR= mkdir $dir/$DIR_DATE      // want to create a date specific dir inside $dir 

But the following code does not work, can you help me out how can I get a result like:

dd/mm/ms/20140211

dd/mm/ms/20140212

and so on..

I realise the code on line 3

CREATE_DIR= mkdir $dir/$DIR_DATE

is not correct and I need to change that, but not sure how


I have updated my code see below:

#!/bin/bash
dir= "/data/mvr/MasterFiles/testing"
DIR_DATE=$(date +%Y%m%d) 
CREATE_DIR="${dir}/${DIR_DATE}"
mkdir "${CREATE_DIR}" || echo "Error creating directory ${CREATE_DIR}"

I reiterate my question, I want to create date specific folder inside an existing directory

Existing directory: /data/mm/ms

Need to create date specific folders for each day inside this existing folder path

eg /data/mm/ms/20140211

/data/mm/ms/20140212

and so on

Upvotes: 0

Views: 294

Answers (2)

jia103
jia103

Reputation: 1134

Looks like you're on the right track. This might work better:

#!/bin/bash
dir=/data/mm/ss
DIR_DATE=`date +%Y%m%d` # not sure on the Y, m, and d -- check man pages

mkdir ${dir}/${DIR_DATE}

# check exit code
if [ $? -ne 0 ]; then
   # error! print something to the user
   exit 1
fi

exit 0

Upvotes: 1

devnull
devnull

Reputation: 123508

You need to refer to Command Substitution:

dir="/data/mm/ms"
DIR_DATE=$(date +%Y%m%d)
CREATE_DIR="${dir}/${DIR_DATE}"
mkdir "${CREATE_DIR}" || echo "Error creating directory ${CREATE_DIR}"

Saying:

var= value

would attempt to execute the command value with the variable var unset.

Additionally, you use the form $(command) for command substitution; backticks is another way. You seem to have combined the two. That is another error.

Upvotes: 3

Related Questions