Saturday, May 28, 2011

Shell Trick: Create a directory and change to it in one command

Often when you create a directory, you are also intending to change to that directory to continue with other operations. This is usually done as two consecutive commands
> mkdir newdir
> cd newdir
But wouldn't this be more easily done in one single command? After all, the same directory name is used in each command.

I created a bash shell functiondetails-1 that does exactly this. I called it "mkcd", since it is basically a combination of "mkdir" and "cd". It is defined as
mkcd () {
if [ $# == 1 ]; then
printf "mkcd %s\n" "${dir}"
if [ -d "${dir}" ]; then
cd "${dir}"
mkdir -p ${dir}
if [ $? == 0 ]; then
cd "${dir}"
printf "Usage: mkcd <dir>\n"
This would be defined in a .bashrc environment initialization file.

This will skip the directory creation if it already exists. It actually uses "mkdir -p" so that it also creates any intermediate directory levels needed. It also only performs the "cd" if directory creation had no errors.

The operation can now be done as
> mkcd newdir

Note that this is a function and not a shell script. Doing it as a script will not work because that runs as a child process, so the directory change happens in a different process and you will remain in the same directory in which you started.

No comments:

Post a Comment