mkdircd the child of mkdir and cd
How often do you find your self typing this?
$ mkdir dirName && cd dirName
- Here is an function you can pop in your
.bashrcor.bashprofile
function mkdircd () { mkdir -p "$@" && cd "$@"; }
In the above passing the
- pflag tomkdirwill also create all directories leading up to the given directory that do not exist already. If the given directory already exists, to ignore the error. from The wiki on mkdir .then the
$@tellsmkdirto use the first argument passed to the function . In this case the dirName or the filetree that you input to the commandmkdircd.After that
&&tellsbashto execute the second command only if the first executes successfully.then we pass the same
$@tocdso that it uses the first argument passed to the function as well.I hope you enjoy your new
mkdircdfunction. You can call it whatever you want ant invoke it from bash like
$ mkdircd coolStuff
$ pwd
$ /coolstuff
pretty nifty eh?
If your not into masking a .bashrcetc. or you just want a portable version here it is.
$ mkdir /path/to/your/newstuff && cd $_
- In the above we pass
$_tocd.$_is the most recent parameter (or the abs path of the command to start the current shell immediately after startup). or the last argument of last command in this case. More info about that here
For ksh and zsh users I got Love for you too
Here are two aliases that do the same thing, I found here on stack overflow for
kshandcshthat I haven't tested because I don't use those shells.I would Love some feedback on them as I would like to know if they are efficient etc.
for
csh
alias mkcd 'mkdir \!^; cd \!^1'
- for
ksh
alias mkcd='_(){ mkdir $1; cd $1; }; _'
- Enjoy
Written by Jupiter St John
Related protips
2 Responses
Actually, the "$@" in the bash function stands for "all arguments to this function, quoted" (the first argument would be "$1"). Running "mkdircd a b" would create two directories, and then cd into the first.
Yes that's exactly what I said.
Below is quoted from my protip above.
then we pass the same $@ to cd so that it uses the first argument passed to the function as well.
then the $@ tells mkdir to use the first argument passed to the function . In this case the dirName or the filetree that you input to the command mkdircd
Passing a second argument to this alias is not the point of this command.
Thanks for pointing that out though :P