what does 'cd $_' mean?

Bash

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

$_ 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.

Solution 2 - Bash

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMukund KumarView Question on Stackoverflow
Solution 1 - BashPSkocikView Answer on Stackoverflow
Solution 2 - BashThe Wall Street BaronView Answer on Stackoverflow