Sunday, August 8, 2010

Bash and CD

Shell scripting gives great advantage to system Administrators and I often use bash in my daily work. Though my work now involves less scripting but for a specific task, i wanted to write a script on my own. The script will take a Project Name as argument, which will would automatically take to that particular Project directory on an NFS share.


For example: Assume that I am working on a Project named MCP1516, then I want my script to take me to that directory. Now you may ask what's the need for a script, just cd command would suffice. But i wanted to do some other things also,

$cd /mnt/projects/*/mcp1516

1. If the nfs share is not mounted , then mount the NFS share under /mnt/projects
2. If the project directory doesn't exist, create the Project directory.
3. Reuse this script with other tasks (probably as a function).

Now the script looked like this:


#!/bin/bash
/bin/mount | grep nfs | grep nfs-server 1> /dev/null
result=`echo $?`

if [ $result -eq 0 ]
then
cd /mnt/projects/*/$1
else
sudo /bin/mount -t nfs nfs-server:/share/projects /mnt/projects
cd /mnt/projects/*/$1
fi


Seems pretty simple script, Now i call the above script as "takemeto"

$takemeto mcp1516

Assuming that the directory already exists , the above script when run should change my "pwd" to /mnt/projects/mcp1516, but (un)fortunately it doesn't.

Now the problem is not in the script but the way bash works and the command "cd" .


First of all, when the script is called, the script is run in a new shell , so the command cd is being run in the "Newly created shell", the parent shell, i.e the shell which called the script has no idea about the commands run in the new shell, next cd is not an external command but it's a bash in-built command . So to execute the bash built commands in the current shell or also called Parent shell, use "source" command.


So if you call the same script using source command , it would change the directory in the current shell

$source takemeto mcp1516

So happy scripting :)

Niranjan