Sometimes when you create a new directory, you may cd to the new directory immediately to perform some work as shown below.
# mkdir -p /tmp/subdir1/subdir2/subdir3 # cd /tmp/subdir1/subdir2/subdir3 # pwd /tmp/subdir1/subdir2/subdir3
Wouldn’t it be nice to combine both mkdir and cd in a single command? Add the following to the .bash_profile and re-login.
$ vi .bash_profile function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; } Now, perform both mkdir and cd at the same time using a single command as shown below: # mkdircd /tmp/subdir1/subdir2/subdir3 [Note: This creates the directory and cd to it automatically] # pwd /tmp/subdir1/subdir2/subdir3
Comments on this entry are closed.
Why don’t You use
mkdir -p "$@" && cd $_;
instead of
mkdir -p "$@" && eval cd "\"\$$#\"";
? Isn’t it a bit clumsy?
>Why don’t You use
>mkdir -p “$@” && cd $_;
>instead of
>mkdir -p “$@” && eval cd “\”\$$#\””;
>? Isn’t it a bit clumsy?
Because it is possible to create directories that contain “space” characters. With your solution it is not possible. Anyway, thanks for the hack.
For us noobs, an explanation of each part of the funtion would be really helpful. What do the different characters mean?
I agree with Seth – and thanks Raksi – ignore the smug Smok
I like S Wawelskis alternative.
I’ve read “use eval with care”.
I also try to not leave spaces in my directory naming scheme.
That is just how I like to work. As always ymmv
The “bash advanced scripting guide” will surely explain
how both versions work.
Why not?
mkdir -p “$@” && cd “$@”
” mkdir -p ” : i know that mkdir will make a directory and what is -p stands for???
@siva the -p causes mkdir to make the intermediate directories as needed if they don’t already exist. For example, say you wanted to run:
~> mkdir ~/Projects/Example/Really_Awesome_Thing
But the directory “Example” doesn’t exist yet then you will get an error. But if you ran:
~> mkdir -p ~/Projects/Example/Really_Awesome_Thing
Then all the necessary directories on the way to ‘Really_Awesome_Thing’ would be created along the way and you would not receive an error.
Cheers,
Bill
Here are some simple options, if you’re not interested in creating an alias. These should work in both Mac and Linux:
mkdir new_directory && cd $_
mkdir -p path/to/new/directory && cd $_
mkdir “new directory” && cd “$_”
mkdir -p “new path/with/spaces in it” && cd “$_”
The first one is probably the most common use case. The main thing to remember for the others is to use the -p switch if you’re creating more than one directory deep, and use double quotes if there’s a space anywhere in the path.