# cd

切换用户当前工作目录。

## 概要

```
cd [-L|[-P [-e]]] [dir]
```

## 主要用途

* 切换工作目录至`dir`。其中`dir`的表示法可以是绝对路径或相对路径。
* 若参数`dir`省略，则默认为使用者的shell变量`HOME`。
* 如果`dir`指定为`~`时表示为使用者的shell变量`HOME`，`.`表示当前目录，`..`表示当前目录的上一级目录。
* 环境变量`CDPATH`是由冒号分割的一到多个目录，你可以将常去的目录的上一级加入到`CDPATH`以便方便访问它们；如果`dir`以`/`开头那么`CDPATH`不会被使用。
* 当`shopt`选项`cdable_vars`打开时，如果`dir`在`CDPATH`及当前目录下均不存在，那么会把它当作变量，读取它的值作为要进入的目录。

## 参数

dir（可选）：指定要切换到的目录。

## 选项

```
-L （默认值）如果要切换到的目标目录是一个符号连接，那么切换到符号连接的目录。
-P 如果要切换到的目标目录是一个符号连接，那么切换到它指向的物理位置目录。
-  当前工作目录将被切换到环境变量OLDPWD所表示的目录，也就是前一个工作目录。
```

## 返回值

返回状态为成功除非无法进入指定的目录。

## 例子

```
cd    # 进入用户主目录；
cd /  # 进入根目录
cd ~  # 进入用户主目录；
cd ..  # 返回上级目录（若当前目录为“/“，则执行完后还在“/"；".."为上级目录的意思）；
cd ../..  # 返回上两级目录；
cd !$  # 把上个命令的参数作为cd参数使用。
```

关于切换到上一个工作目录的说明

```
cd -
# 命令会首先显示要切换到的目标目录，然后再进入。
cd ${OLDPWD}
# 命令会直接切换到上一个工作目录。
```

关于`CDPATH`

```
# 设置桌面文件夹作为CDPATH的值。
CDPATH='~/Desktop'
# 假设我们接下来要演示涉及到的路径~和~/Desktop下没有test3文件夹，现在新建它们。
mkdir ~/test3
mkdir ~/Desktop/test3
# 进入~目录。
cd ~
# 进入test3目录。
cd test3
# 执行后显示~/Desktop/test3并进入该目录，而不是~目录的test3目录。
# 如果CDPATH存在值，那么优先在CDPATH中查找并进入第一个匹配成功的，如果全部失败那么最后尝试当前目录。
```

关于`cdable_vars`

```
# 打开选项。
shopt -s cdable_vars
# 假设当前路径以及CDPATH没有名为new_var的目录。
new_var='~/Desktop'
# 尝试进入。
cd new_var
# 关闭选项。
shopt -u cdable_vars
```

### 注意

1. 该命令是bash内建命令，相关的帮助信息请查看`help`命令。
2. 建议您在编写脚本的过程中如有必要使用`cd`命令时，请增加必要的注释以用于提醒阅读者当前工作目录，以免出现诸如`找不到文件`这类问题的发生。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hezhiqiang.gitbook.io/linux/ming-ling/cd.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
