When you are in the directory ~/test/basic_unix
and invoke your script, your mkdir "$createdep"
command creates that folder in ~/test/basic_unix
because that's the current directory, that's where you ran the script from. However, when you run that script from cron, the directory you start with is your home directory, ~
, so your mkdir
command creates the folder there.
Your confusion might be because you think that since your script is under ~/test/basic_unix/createfiles.sh
, then the folders will always be created there, but that's incorrect. It's not about where the script is located, it's about where you run the script from. To give you an example, make a directory ~/testing2
, then cd ~/testing2
, then call your script using sh ~/test/basic_unix_createfiles.sh
. You'll find that your folders are being created under ~/testing2
, not ~/test/basic_unix
. Why? Because that's where you ran the script from, and since your mkdir
command is using a relative path, i.e. since your mkdir
command is like this: mkdir foldername
, it creates it in working directory.
To fix your problem, the easiest way is to cd
to where you want to create the folders at the very beginning, so your script would look like this:
#THIS CODE WILL CREATE A DIRECTORY WITH TIME OF CREATION AS PART OF DIRECTORY NAME
cd /home/adhikarisubir/test/basic_unix #this is the new line added, the rest is the same
echo "The time is $(date +%H_%M_%S)"
now=$(date +%H_%M_%S)
echo $now
echo $(pwd)
createdep=nowt_$now
echo "$createdep"
mkdir "$createdep"
cd nowt_$now
echo "Current directory is $(pwd)"
echo "This is a text file which will contain the createtime" > Newtxt.txt
sed -i "s/createtime/$(date '+%H:%M:%S')/g" Newtxt.txt
Another way to fix your problem is to change your mkdir
command to use an absolute path. So your script would look like this:
#THIS CODE WILL CREATE A DIRECTORY WITH TIME OF CREATION AS PART OF DIRECTORY NAME
echo "The time is $(date +%H_%M_%S)"
now=$(date +%H_%M_%S)
echo $now
echo $(pwd)
#createdep=nowt_$now
createdep=/home/adhikarisubir/test/basic_unix/nowt_$now #createdep is now an absolute path
echo "$createdep"
mkdir "$createdep"
#cd nowt_$now
cd $createdep #this cd command now cds to $createdep
echo "Current directory is $(pwd)"
echo "This is a text file which will contain the createtime" > Newtxt.txt
sed -i "s/createtime/$(date '+%H:%M:%S')/g" Newtxt.txt
It's better to always use absolute paths, so always use /home/adhikarisubir/test/basic_unix
instead of saying test/basic_unix
.
Note: I'm assuming your home directory is /home/adhikarisubir
.