Tuesday, 21 April 2009

Linux Shell Script - Changing Directory

I found out that changing directory in the shell script file does not affect the shell in which it was called.
When you run a shell script, the script in run in another shell session.

I will explain with an example.

This is the contents of my script, which is called "mymkdir":
#!/bin/bash
mkdir $1
cd $1


So the goal of this script was to create a new directory and the name of this will be passed in as parameter. And afterwards we would like to change into that directory.
But if you try and run this script nothing will happen. It will create the new directory, but it wont change into that directory. You will remain in the same location.
This is how I ran the script:
> mymkdir newFolder

Solution
To use the keyword "source" before running the script.
> source mymkdir newFolder

Now it should work as expected. A new directory called "newFolder" has been created and the shells present working directory is now inside the new folder.

No comments: