Monday, February 24, 2014

md()

So...I kind of lied in my first post. It was a little white lie. I didn't actually do a mkdir and then a cd.

In my configuration files for bash I have a function defined that can do this for me.

$ type md
md is a function
md ()
{
    /bin/mkdir -p "$1" && builtin cd "$1"
}

Breaking this down is pretty easy.

Use the mkdir command with the -p option for two reasons:
  1. intermediate directories will be created if I specify a long path
  2. errors will not pollute the terminal in almost all cases
$1 is a positional parameter specifying an item passed after calling the script or function. In this case it will be the directory I want to create and change into.

&& is a control operator that ensures that the cd will only execute if the mkdir exited successfully.

Specifying the builtin cd is only really necessary because I have made a function for my own cd which I might cover in another post sometime. It also has the side benefit of ensuring we use the builtin instead of /usr/bin/cd which will be quite a bit faster.

So what does all this mean? I can do the following at the command line instead of the two separate commands at beginning of my first post.

$ md src
$ pwd
/Users/ryan/src

No comments:

Post a Comment