163

is there any way (what is the easiest way in bash) to combine the following:

mkdir foo
cd foo

The manpage for mkdir does not describe anything like that, maybe there is a fancy version of mkdir? I know that cd has to be shell builtin, so the same would be true for the fancy mkdir...

Aliasing?

  • You can't alias two commands together directly. – goldilocks Apr 18 '14 at 14:05
133

Function?

mkcdir ()
{
    mkdir -p -- "$1" &&
      cd -P -- "$1"
}

Put the above code in the ~/.bashrc or another file sourced by the ~/.bashrc. Then restart the terminal for changes to apply.

After that simply run mkcdir foo or mkcdir "nested/path/in quotes".

Notes:

  • "$1" is the first argument of the mkcdir command. Quotes around it protects the argument if it has spaces or other special characters.
  • -- makes sure the passed name for the new directory is not interpreted as an option to mkdir or cd, giving the opportunity to create a directory that starts with - or --.
  • -p used on mkdir makes it create extra directories if they do not exist yet, and -P used makes cd resolve symbolic links.
| improve this answer | |
  • 10
    quotes around "$1" will protect the argument if it has spaces. – glenn jackman Apr 18 '14 at 13:33
  • 10
    and put this in .bashrc? – Jasper Apr 18 '14 at 14:05
  • 5
    What's the purpose of --? – Zaz Nov 12 '16 at 21:25
  • 16
    @Zaz -- is used to make sure that the following parameters are not parsed as a options to modify the behaviour of the command. In this case it makes sure the passed name for the new directory is not interpreted as an option to mkdir or cd, giving the option to create a directory that starts with - or -- . – immeëmosol Jan 4 '17 at 11:12
  • 18
    In case someone's wondering, the -P used makes cd resolve symbol links. The -p used on mkdir makes it create extra directories if they do not exists yet. – immeëmosol Jan 4 '17 at 11:14
286

I think creating a function is the most appropriate way to do this, but just for listing all alternative ways, you could write:

mkdir foo && cd "$_"

$_is a special parameter that holds the last argument of the previous command. The quote around $_ make sure it works even if the folder name contains spaces.

Why use double quotes?

In some shells, such as zsh, the double quotes surrounding the $_ are not necessary even when the directory name contains spaces. They are required for this command to work in bash, however.

For example, running this command in bash 3.2.57 on macOS 10.13.6:

mkdir "my directory" && cd $_

results in this output:

bash: cd: my: No such file or directory

However, if we surround $_ with double quotes, the command returns successfully.

bash-3.2$ mkdir "my directory" && cd "$_"
bash-3.2$ echo $?
0
bash-3.2$
| improve this answer | |
  • 3
    Same line version of $!, in this case, is !#:1. i.e. "$_" can be replaced with !#:1. – antak Dec 7 '16 at 5:33
  • 2
    @nyxee $_'s value will be foo in this example. If I had instead typed mkdir workspace, the value of $_ would have been workspace, and cd "$_" would change our current directory to the newly created workspace. Does that make sense? – Zajn Feb 23 '17 at 15:56
  • 1
    why did you add the double quotation ? I just tried and It works without it. Also, it makes it look really ugly and might discourage some people – Suhaib Aug 9 '17 at 5:38
  • 1
    @SHiON Adding double-quotes is necessary in bash when creating a directory that contains spaces. Since the question is tagged for bash, I answered accordingly. – Zajn Oct 2 '18 at 18:52
  • 2
    @harperville The reason for the error at the end of the answer is to demonstrate the need for quotes surrounding $_ in certain shells, namely bash. Perhaps I should re-word that section to more clearly state that without the "$_", that is the error you will see. – Zajn Jan 15 '19 at 20:52
22

Bash (using word designators):

/tmp/bug$ mkdir "some dir"
/tmp/bug$ cd !$
cd "some dir"
/tmp/bug/some dir$ 

!$ expands to the last argument of the previous line in the history. If you have parameters in between, then you can use !:1 for the first argument, !:2 forthe second argument, etc.

From bash(1):

Event Designators

An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list.

! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin).

[..]

Word Designators

Word designators are used to select desired words from the event. A : separates the event specification from the word designator. [..]

[..]
n The n-th word.
^ The first argument. That is, word 1.
$ The last word. This is usually the last argument, but will expand to the zeroth word if there is only one word in the line.

| improve this answer | |
  • I think that "!:1" loses vs "$firstfewcharactersofnewdir+TAB" in most cases... – Jasper Apr 18 '14 at 14:19
  • @Jasper I seldomly use !:1, but it is an option if you have a path with a non-unique prefix. – Lekensteyn Apr 18 '14 at 14:34
  • 4
    !$ is shorter and easier to type on many keyboards. See also <Alt-.> or <Alt-_> – Stéphane Chazelas Apr 18 '14 at 14:51
  • 1
    @StephaneChazelas What is the difference between Alt+. and Alt+_? – Bernhard Apr 18 '14 at 19:03
  • 1
    @bernard you can move forward and backward in the parameter list. See the manual page of bash. – Lekensteyn Apr 18 '14 at 19:58
10

These other lads are just making life complicated, here it is:

eval {mkdir,cd}\ FOLDER\;
| improve this answer | |
  • 2
    I really wanted to make a directory called 'FOLDER && rm ../something'. But eval won't let me :*( Tragically, may have to choose complicated in the battle of complicated vs evil. – user60101 Apr 19 '14 at 2:14
  • @BroSlow, well then you'll have to find another OS, since having a slash in a filename has never been allowed! as for the other characters they work just fine if escaped. – Sean D Apr 19 '14 at 10:20
  • 1
    @SeanD You're missing my point. Using eval with user input is generally a bad idea and eval will process FOLDER && rm ../something in place of FOLDER without complaint. Or for another variant, how about "FOLDER && rm -r $HOME" – user60101 Apr 19 '14 at 17:28
  • 1
    @BroSlow This isn't using eval with user input, so it's fine. Don't cargo cult. – Miles Rout Jan 30 '16 at 6:56
  • 2
    @MilesRout If you only ever use it for a directory called FOLDER, sure, this is fine. That's not the point, if you use it with variable input (which you almost certainly are going to), the results for weird directory names can at best cause unexpected results, at worst pose a security risk. – user60101 Feb 1 '16 at 1:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.