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?
The cd command, also known as chdir (change directory), is a command-line shell command used to change the current working directory in various operating systems.
In Linux 'cd' (Change Directory) command is one of the most important and most widely used command for newbies as well as system administrators. For admins on a headless server, 'cd' is the only way to navigate to a directory to check log, execute a program/application/script and for every other task.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Continuous delivery (CD) is the automated delivery of completed code to environments like testing and development. CD provides an automated and consistent way for code to be delivered to these environments. Continuous deployment is the next step of continuous delivery.
$_
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With