57

I have seen this command in a tutorial to create a new directory:

mkdir my-new-project && cd $_

I know mkdir my-new-project command is used to create a new directory, but what does cd $_ do?

2 Answers 2

87

$_ expands to the last argument to the previous simple command* or to previous command if it had no arguments.

mkdir my-new-project && cd $_

^ Here you have a command made of two simple commands. The last argument to the first one is my-new-project so $_ in the second simple command will expand to my-new-project.

To give another example:

echo a b; echo $_
#Will output:
#a b
#b

In any case, mkdir some_dir && cd $_ is a very common combo. If you get tired of typing it, I think it's a good idea to make it a function:

mkdircd() {
  #Make path for each argument and cd into the last path 
  mkdir -p "$@" && cd "$_" 
}

* The bash manual defines a simple command as "a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator. " where control operator refers to one of || & && ; ;; ( ) | |& <newline>.

In practice$_ works like I've described but only with ||, &&, ;, or newline as the control operator.

9

7. How to create directory and switch to it using single command. As you might already know, the && operator is used for executing multiple commands, and $_ expands to the last argument of the previous command.

Quickly, if you want, you can create a directory and also move to that directory by using a single command. To do this, run the following command:

$ mkdir [dir-name] && cd $_

For those coming from Udacity's Version Control with Git, HowToForge offers a great explanation, here.

1
  • 2
    One usage example is git clone https://github.com/udacity/course-git-blog-project blog-project && cd $_. This will clone a repository and open inside the newly created directory.
    – low_vision
    Commented Mar 26, 2018 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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