Well after reading replies to my question, I tried my luck with bash scripting. I got a script that has solved my problem.
Thanks to sycamorex, Poetics and the trooper for helping me.
I am posting my script and a little bit explanation here for some other newbie like me :
I named the following script mkdirNcd.sh
Code:
#!/bin/sh
if [ $# = 0 ]
then
echo No Folder name given
elif [ -d $1 ]
then
echo Folder already exists
cd $1
else
echo Creating a new folder
mkdir -p $1
cd $1
fi
#!/bin/sh This line is simply a comment
$# This is a variable which has the number of parameters passed to the script.
if [ $# = 0 ]
then
echo No Folder name given
The above portion just checks whether any folder name was given or not. In case it wasn't it prints "No Folder name given"
$1 This variable contains first parameter with which we are concerned.
elif is same as else if
elif [ -d $1 ]
then
echo Folder already exists
cd $1
The above portion checks whether the given folder exists or not. If it exists it cd into it.
else
echo Creating a new folder
mkdir -p $1
cd $1
The above portion creates a new folder and cd into it.
fi This tells the end of if structure
A problem
There is a problem with using cd in a script. Actually all scripts on execution make their own sub-shell. Once the script ends, control exits out of that sub-shell and we are back at the original shell.
Now when we use cd in a script. That script creates its own sub-shell. In that sub-shell control cd into the new folder. But once script ends, we are back to our original shell. Hence there is no cd into new folder.
To solve it we can use
Code:
$ source mkdirNcd.sh
or
Making it accessible globally
For that, I just had to put it into a folder defined in $PATH
Code:
$ echo $PATH
/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/Thomas/bin
I selected the last folder
/home/Thomas/bin; created bin in my home folder and copied mkdirNcd.sh into it.
Now I just had to write
Code:
$ . mkdirNcd.sh newFolder
to get the desired effect. But it feels like a burden to write the whole thing with a dot preceding it, so I made an alias of it.
Making an Alias
I added following line to my .bashrc file
Code:
alias thomas='. mkdirNcd.sh'
Now I just have to write
Code:
$thomas Chemistry
Creating a new folder
$pwd
/home/Thomas/Chemistry