Create a directory when its non-existent

Hi
I need to create a directory when its non-existent
Having an issue with the code here because it doesn't work
can someone point what and how to change, please.

---------- Post updated at 11:08 AM ---------- Previous update was at 11:07 AM ----------

filelist=project_name/files/
source_dir=dw_icon/Temp/
target_dir=dw_icon/Temp/ArchiveFiles
if [ ! -d {source_dir} ] 
then
mkdir -p {target_dir}
else
echo"already ArchiveFiles folder created"
fi

find ${filelist} -name "*" -mtime +30 -exec cp {} ${target_dir}/ \;

could you please post the code please?

---------- Post updated at 09:40 PM ---------- Previous update was at 09:38 PM ----------

Where is PROJ_NAME variable getting populated in your script?

PROJ_NAME=dw_icon

Please use code tags when posting code.

Apart from PROJ_NAME unintialized you are missing two dollar signs:

filelist=project_name/files/
source_dir=${PROJ_NAME}/Temp/
target_dir=${PROJ_NAME}/Temp/ArchiveFiles"
if [ ! -d ${source_dir} ] 
then
mkdir -p ${target_dir}
else
echo"already ArchiveFiles folder created"  #will never get here
fi

find ${filelist} -name "*" -mtime +30 -exec cp {} ${target_dir}/ \;

The else clause of your if statement will never get executed; mkdir -p dir will return 0 whether the directory exists or not. You have to omit the -p switch if you want to test on this:

if [ ! -d $source_dir ] 
then 
    mkdir $target_dir
else
     echo"already ArchiveFiles folder created"
fi

Which can be consolidated into:

if ! mkdir  $target_dir 2>/dev/null ; then #the redirection gets rid of error message
    echo "Dir $target_dir exists already"
fi
1 Like
if [ ! -d ${source_dir} ] 
then
mkdir -p ${target_dir}

That's a bit redundant. mkdir -p does that without the if.

So, just mkdir -p /path/to/folder will create a folder if it doesn't exist, and silently do nothing if it already does.

It could fail because the directodry already exists, but it could also fail due to permissions, read-only filesystem, full filesystem, ...

Regards,
Alister

1 Like

I'm not sure I understand the logics - if SOURCE_DIR does not exist then create TARGET_DIR? Admittedly the target_dir is contained in source_dir, so when it's created, so is source_dir, but when not so, the echo in the else branch will be wrong, source_dir can exist without Archivefiles.