1

在 Linux 中使用 cd 命令

 1 year ago
source link: https://www.51cto.com/article/759522.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
46a242e84c3bfcebe786906b95d61eb65a1e26.jpg

Linux 中的 cd 命令用于更改目录。cd 实际上是“更改目录change directories”的缩写。

这是你必须了解的 基本 Linux 命令之一。

使用 cd 命令非常简单:

cd path_to_directory

不可能比这更简单了,对吧。

然而,你应该理解它的路径部分,以便轻松地浏览 文件系统 而不会感到困惑。

这是绝对路径和相对路径的快速回顾:

Absolute vs relative path in Linux

Absolute vs relative path in Linux

如果你需要更多细节,我建议你阅读这篇文章:

Linux 上的绝对路径和相对路径有什么不同

让我们看一些使用 cd 命令的示例。

使用绝对路径更改目录

从视觉上看会更容易理解。看下图。

Absolute path travel to the python directory

Absolute path travel to the python directory

我当前的位置是我的主目录(/home/abhishek),我必须进入 scripts 目录中的 python 目录。

假设我想使用绝对路径。python 目录的绝对路径是 /home/abhishek/scripts/python

cd /home/abhishek/scripts/python
cd command with absolute path

cd command with absolute path

使用相对路径更改目录

让我们举同样的例子,但这次我将采用相对路径。

Relative path example

Relative path example

我的主目录到 python 目录的相对路径是 scripts/python。让我们用这个:

cd scripts/python
cd command with relative path

cd command with relative path

进入上级目录

到目前为止,你一直在进入下级。如果你必须进入上级目录怎么办?

假设你位于 /home/abhishek/scripts/python 中,并且必须将目录添加到 scripts

f3015af73bb3b98d012464bfa7107520821875.png

使用绝对路径始终是一种选择,但它相当冗长。相反,你可以使用特殊的目录符号 ..。双点 (..)表示父目录或上一级目录。单点(.)表示当前目录。

cd ..

这是一个例子:

cd up a directory

cd up a directory

你可以使用 .. 在 Linux 文件系统层次结构中向上移动路径。

假设我在上图中的 python 目录中,想要进入 code 目录。这是我能做的:

cd ../../code
Go up the directory using cd command

Go up the directory using cd command

进入主目录

如果你在所有这些目录切换中感到迷失并想回到主目录,有很多简单的快捷方式。

事实上,最简单的就是使用不带任何选项的 cd 命令。

cd

这将使你从文件系统上的任何位置返回主目录。

或者,你可以使用 ~ 符号,表示主目录。

cd ~
Use cd to go back home

Use cd to go back home

进入根目录

尽管你不会像前一个那样经常使用它,但了解一下仍然有好处。

如果你想返回文件系统开始的根目录,请使用以下命令:

cd /

这里不涉及“魔法”。当放在路径开头使用时,/ 表示根。不要将它与路径分隔符混淆。

Paths in Linux

Paths in Linux

切换回上一级目录

这是一个救命稻草,或者我应该说是“省时稻草”。当你深入目录结构,然后转到另一个目录,然后你觉得需要返回到以前的位置时,此快捷方式会有所帮助。

cd -

还不清楚吗? 让我举个例子。

我位于 /etc/apt/sources.list.d。从这里,进入 /home/abhishek/scripts/python 来处理我的代码。然后我意识到我必须再次检查 /etc/apt/sources.list.d 目录中的某些内容。

通常的方法是这样做,这让我再次输入所有路径:

Go back to previous directory

Go back to previous directory

但聪明的方法是使用这个:

Use cd - to go back to previous directory

Use cd - to go back to previous directory

看吧,无需再次输入冗长的路径。如期工作!

🏋️ 练习时间

如果你想练习 cd 命令,这里有一些练习供你使用。

  • 打开终端并进入 /var/log 目录。检查目录内容。你看到了什么?
  • 现在,进入 /var 目录。这是一个上级目录。
  • 从这里返回你的主目录。

这些内容足以让你熟悉 cd 命令。以下是你应该了解的其他一些重要命令。

每个 Ubuntu 用户都应该知道的 31 条 Linux 命令

如果你有疑问或建议,请告诉我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK