bash 'cd $_' 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30154694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:58:12  来源:igfitidea点击:

what does 'cd $_' mean?

bash

提问by Mukund Kumar

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

我在创建新目录的教程中看到了这个命令:

mkdir my-new-project && cd $_

I know mkdir my-new-projectcommand is used to create a new directory, but what does cd $_do?

我知道mkdir my-new-projectcommand 用于创建一个新目录,但是有什么作用cd $_呢?

回答by PSkocik

$_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-projectso $_in the second simple commandwill expand to my-new-project.

^ 这里有一个由两个简单命令组成的命令。的最后一个参数,第一个是my-new-project因此$_在第二简单的命令将扩大到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:

无论如何,mkdir some_dir && cd $_是一个很常见的组合。如果你厌倦了打字,我认为把它变成一个函数是个好主意:

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


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

* bash 手册将一个简单的命令定义为“一系列可选的变量赋值,后跟空格分隔的单词和重定向,并由控制运算符终止其中控制运算符指的是|| & && ; ;; ( ) | |& <newline>.

In practice$_works like I've described but only with ||, &&, ;, or newlineas the control operator.

在实际应用中$_的作品像我描述,但只能用||&&;换行的控制操作。

回答by Kaotikus

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.

7. 如何创建目录并使用单个命令切换到该目录。您可能已经知道,&& 运算符用于执行多个命令,而 $_ 扩展为前一个命令的最后一个参数。

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.

对于那些来自 Udacity 的 Git 版本控制的人,HowToForge 提供了一个很好的解释,这里