Bash 的 cd 命令

作者:hubenchang0515日期:2025/11/6

#Bash 的 cd 命令

1cd [-L|-P] [DIRECTORY]
2

功能

切换工作目录。

类型

Bash 内置命令。

参数

  • OPTION 选项:
    • -L - 逻辑路径;在跟踪符号链接之前解析 ..(默认)
    • -P - 物理路径;在跟踪符号链接之后解析 ..
  • DIRECTORY - 要切换到的目录路径;省略表示切换到用户目录,- 表示切换到上次的工作目录

#示例

基本示例

1$ pwd                       # 查看当前路径
2/home/user/primers
3$ cd bash                   # 相对路径
4$ pwd 
5/home/user/primers/bash
6$ cd -                      # 切换回之前的目录
7$ pwd 
8/home/user/primers
9$ cd /etc                   # 绝对路径
10$ pwd 
11/etc
12

符号链接

1$ pwd                       # 查看当前路径
2/home/user/primers
3$ ln -s /usr/lib lib        # 创建符号链接
4$ cd lib                    # 进入 lib
5$ pwd 
6/home/user/primers/bash/lib
7$ cd ..                     # 返回上级目录
8$ cd -P lib                 # 进入 lib,跟踪符号链接
9$ pwd 
10/usr/lib
11

#相关命令

命令说明
pushd将当前工作目录压入栈顶,并切换工作目录
popd将目录栈的栈顶移除,并切换工作目录
dirs查看当前工作目录和目录栈

#推荐阅读

#手册

显示

1CD(1P)                  POSIX Programmer's Manual                  CD(1P)
2PROLOG         top
3       This manual page is part of the POSIX Programmer's Manual.  The
4       Linux implementation of this interface may differ (consult the
5       corresponding Linux manual page for details of Linux behavior), or
6       the interface may not be implemented on Linux.
7NAME         top
8       cd  change the working directory
9SYNOPSIS         top
10       cd [-L|-P] [directory]
11
12       cd -
13DESCRIPTION         top
14       The cd utility shall change the working directory of the current
15       shell execution environment (see Section 2.12, Shell Execution
16       Environment) by executing the following steps in sequence. (In the
17       following steps, the symbol curpath represents an intermediate
18       value used to simplify the description of the algorithm used by
19       cd.  There is no requirement that curpath be made visible to the
20       application.)
21
22        1. If no directory operand is given and the HOME environment
23           variable is empty or undefined, the default behavior is
24           implementation-defined and no further steps shall be taken.
25
26        2. If no directory operand is given and the HOME environment
27           variable is set to a non-empty value, the cd utility shall
28           behave as if the directory named in the HOME environment
29           variable was specified as the directory operand.
30
31        3. If the directory operand begins with a <slash> character, set
32           curpath to the operand and proceed to step 7.
33
34        4. If the first component of the directory operand is dot or dot-
35           dot, proceed to step 6.
36
37        5. Starting with the first pathname in the <colon>-separated
38           pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if
39           the pathname is non-null, test if the concatenation of that
40           pathname, a <slash> character if that pathname did not end
41           with a <slash> character, and the directory operand names a
42           directory. If the pathname is null, test if the concatenation
43           of dot, a <slash> character, and the operand names a
44           directory. In either case, if the resulting string names an
45           existing directory, set curpath to that string and proceed to
46           step 7. Otherwise, repeat this step with the next pathname in
47           CDPATH until all pathnames have been tested.
48
49        6. Set curpath to the directory operand.
50
51        7. If the -P option is in effect, proceed to step 10. If curpath
52           does not begin with a <slash> character, set curpath to the
53           string formed by the concatenation of the value of PWD, a
54           <slash> character if the value of PWD did not end with a
55           <slash> character, and curpath.
56
57        8. The curpath value shall then be converted to canonical form as
58           follows, considering each component from beginning to end, in
59           sequence:
60
61            a. Dot components and any <slash> characters that separate
62               them from the next component shall be deleted.
63
64            b. For each dot-dot component, if there is a preceding
65               component and it is neither root nor dot-dot, then:
66
67                i.  If the preceding component does not refer (in the
68                    context of pathname resolution with symbolic links
69                    followed) to a directory, then the cd utility shall
70                    display an appropriate error message and no further
71                    steps shall be taken.
72
73               ii.  The preceding component, all <slash> characters
74                    separating the preceding component from dot-dot, dot-
75                    dot, and all <slash> characters separating dot-dot
76                    from the following component (if any) shall be
77                    deleted.
78
79            c. An implementation may further simplify curpath by removing
80               any trailing <slash> characters that are not also leading
81               <slash> characters, replacing multiple non-leading
82               consecutive <slash> characters with a single <slash>, and
83               replacing three or more leading <slash> characters with a
84               single <slash>.  If, as a result of this canonicalization,
85               the curpath variable is null, no further steps shall be
86               taken.
87
88        9. If curpath is longer than {PATH_MAX} bytes (including the
89           terminating null) and the directory operand was not longer
90           than {PATH_MAX} bytes (including the terminating null), then
91           curpath shall be converted from an absolute pathname to an
92           equivalent relative pathname if possible. This conversion
93           shall always be considered possible if the value of PWD, with
94           a trailing <slash> added if it does not already have one, is
95           an initial substring of curpath.  Whether or not it is
96           considered possible under other circumstances is unspecified.
97           Implementations may also apply this conversion if curpath is
98           not longer than {PATH_MAX} bytes or the directory operand was
99           longer than {PATH_MAX} bytes.
100
101       10. The cd utility shall then perform actions equivalent to the
102           chdir() function called with curpath as the path argument. If
103           these actions fail for any reason, the cd utility shall
104           display an appropriate error message and the remainder of this
105           step shall not be executed. If the -P option is not in effect,
106           the PWD environment variable shall be set to the value that
107           curpath had on entry to step 9 (i.e., before conversion to a
108           relative pathname). If the -P option is in effect, the PWD
109           environment variable shall be set to the string that would be
110           output by pwd -P.  If there is insufficient permission on the
111           new directory, or on any parent of that directory, to
112           determine the current working directory, the value of the PWD
113           environment variable is unspecified.
114
115       If, during the execution of the above steps, the PWD environment
116       variable is set, the OLDPWD environment variable shall also be set
117       to the value of the old working directory (that is the current
118       working directory immediately prior to the call to cd).
119OPTIONS         top
120       The cd utility shall conform to the Base Definitions volume of
121       POSIX.1‐2017, Section 12.2, Utility Syntax Guidelines.
122
123       The following options shall be supported by the implementation:
124
125       -L        Handle the operand dot-dot logically; symbolic link
126                 components shall not be resolved before dot-dot
127                 components are processed (see steps 8.  and 9. in the
128                 DESCRIPTION).
129
130       -P        Handle the operand dot-dot physically; symbolic link
131                 components shall be resolved before dot-dot components
132                 are processed (see step 7. in the DESCRIPTION).
133
134       If both -L and -P options are specified, the last of these options
135       shall be used and all others ignored. If neither -L nor -P is
136       specified, the operand shall be handled dot-dot logically; see the
137       DESCRIPTION.
138OPERANDS         top
139       The following operands shall be supported:
140
141       directory An absolute or relative pathname of the directory that
142                 shall become the new working directory. The
143                 interpretation of a relative pathname by cd depends on
144                 the -L option and the CDPATH and PWD environment
145                 variables. If directory is an empty string, the results
146                 are unspecified.
147
148       -         When a <hyphen-minus> is used as the operand, this shall
149                 be equivalent to the command:
150
151                     cd "$OLDPWD" && pwd
152
153                 which changes to the previous working directory and then
154                 writes its name.
155STDIN         top
156       Not used.
157INPUT FILES         top
158       None.
159ENVIRONMENT VARIABLES         top
160       The following environment variables shall affect the execution of
161       cd:
162
163       CDPATH    A <colon>-separated list of pathnames that refer to
164                 directories. The cd utility shall use this list in its
165                 attempt to change the directory, as described in the
166                 DESCRIPTION. An empty string in place of a directory
167                 pathname represents the current directory. If CDPATH is
168                 not set, it shall be treated as if it were an empty
169                 string.
170
171       HOME      The name of the directory, used when no directory
172                 operand is specified.
173
174       LANG      Provide a default value for the internationalization
175                 variables that are unset or null. (See the Base
176                 Definitions volume of POSIX.1‐2017, Section 8.2,
177                 Internationalization Variables for the precedence of
178                 internationalization variables used to determine the
179                 values of locale categories.)
180
181       LC_ALL    If set to a non-empty string value, override the values
182                 of all the other internationalization variables.
183
184       LC_CTYPE  Determine the locale for the interpretation of sequences
185                 of bytes of text data as characters (for example,
186                 single-byte as opposed to multi-byte characters in
187                 arguments).
188
189       LC_MESSAGES
190                 Determine the locale that should be used to affect the
191                 format and contents of diagnostic messages written to
192                 standard error.
193
194       NLSPATH   Determine the location of message catalogs for the
195                 processing of LC_MESSAGES.
196
197       OLDPWD    A pathname of the previous working directory, used by cd
198                 -.
199
200       PWD       This variable shall be set as specified in the
201                 DESCRIPTION. If an application sets or unsets the value
202                 of PWD, the behavior of cd is unspecified.
203ASYNCHRONOUS EVENTS         top
204       Default.
205STDOUT         top
206       If a non-empty directory name from CDPATH is used, or if cd - is
207       used, an absolute pathname of the new working directory shall be
208       written to the standard output as follows:
209
210           "%s\n", <new directory>
211
212       Otherwise, there shall be no output.
213STDERR         top
214       The standard error shall be used only for diagnostic messages.
215OUTPUT FILES         top
216       None.
217EXTENDED DESCRIPTION         top
218       None.
219EXIT STATUS         top
220       The following exit values shall be returned:
221
222        0    The directory was successfully changed.
223
224       >0    An error occurred.
225CONSEQUENCES OF ERRORS         top
226       The working directory shall remain unchanged.
227
228       The following sections are informative.
229APPLICATION USAGE         top
230       Since cd affects the current shell execution environment, it is
231       always provided as a shell regular built-in. If it is called in a
232       subshell or separate utility execution environment, such as one of
233       the following:
234
235           (cd /tmp)
236           nohup cd
237           find . -exec cd {} \;
238
239       it does not affect the working directory of the caller's
240       environment.
241
242       The user must have execute (search) permission in directory in
243       order to change to it.
244EXAMPLES         top
245       The following template can be used to perform processing in the
246       directory specified by location and end up in the current working
247       directory in use before the first cd command was issued:
248
249           cd location
250           if [ $? -ne 0 ]
251           then
252               print error message
253               exit 1
254           fi
255           ... do whatever is desired as long as the OLDPWD environment variable
256               is not modified
257           cd -
258RATIONALE         top
259       The use of the CDPATH was introduced in the System V shell. Its
260       use is analogous to the use of the PATH variable in the shell. The
261       BSD C shell used a shell parameter cdpath for this purpose.
262
263       A common extension when HOME is undefined is to get the login
264       directory from the user database for the invoking user. This does
265       not occur on System V implementations.
266
267       Some historical shells, such as the KornShell, took special
268       actions when the directory name contained a dot-dot component,
269       selecting the logical parent of the directory, rather than the
270       actual parent directory; that is, it moved up one level toward the
271       '/' in the pathname, remembering what the user typed, rather than
272       performing the equivalent of:
273
274           chdir("..");
275
276       In such a shell, the following commands would not necessarily
277       produce equivalent output for all directories:
278
279           cd .. && ls      ls ..
280
281       This behavior is now the default. It is not consistent with the
282       definition of dot-dot in most historical practice; that is, while
283       this behavior has been optionally available in the KornShell,
284       other shells have historically not supported this functionality.
285       The logical pathname is stored in the PWD environment variable
286       when the cd utility completes and this value is used to construct
287       the next directory name if cd is invoked with the -L option.
288FUTURE DIRECTIONS         top
289       None.
290SEE ALSO         top
291       Section 2.12, Shell Execution Environment, pwd(1p)
292
293       The Base Definitions volume of POSIX.1‐2017, Chapter 8,
294       Environment Variables, Section 12.2, Utility Syntax Guidelines
295
296       The System Interfaces volume of POSIX.1‐2017, chdir(3p)
297COPYRIGHT         top
298       Portions of this text are reprinted and reproduced in electronic
299       form from IEEE Std 1003.1-2017, Standard for Information
300       Technology -- Portable Operating System Interface (POSIX), The
301       Open Group Base Specifications Issue 7, 2018 Edition, Copyright
302       (C) 2018 by the Institute of Electrical and Electronics Engineers,
303       Inc and The Open Group.  In the event of any discrepancy between
304       this version and the original IEEE and The Open Group Standard,
305       the original IEEE and The Open Group Standard is the referee
306       document. The original Standard can be obtained online at
307       http://www.opengroup.org/unix/online.html .
308
309       Any typographical or formatting errors that appear in this page
310       are most likely to have been introduced during the conversion of
311       the source files to man page format. To report such errors, see
312       https://www.kernel.org/doc/man-pages/reporting_bugs.html .
313
314IEEE/The Open Group                2017                            CD(1P)
315

Bash 的 cd 命令》 是转载文章,点击查看原文


相关推荐


规训 AI Agent 实践
清沫2025/11/1

AI 编程工具目前的发展可谓是三十年河东三十年河西,时不时就会有爆炸性的能力提升。初步使用,效果极其惊艳,随着使用的加深,就会发现 AI 会时不时犯蠢。本文总结 AI 协作的一些实践,希望帮助你让 AI 成为更可靠的编程伙伴。 别着急动手, 先制定计划 很多人使用 AI 编程工具时,习惯直接让 AI "帮我实现 xxx 功能",然后 AI 就立即开始写代码。这种方式在简单需求下可以工作,但面对复杂任务时容易出问题。等待十几分钟漫长的生码过程后,发现结果与预期相差甚远,既费时又费 token。 因


Nginx 高效动静分离:从原理到实战
银河技术2025/10/30

Nginx 高效动静分离:从原理到实战 Nginx 动静分离是 Web 性能优化中的经典策略,合理配置可显著提升网站性能、减轻应用服务器压力,并便于后续扩展与运维。本文将从 原理、配置、实战案例 以及 优化技巧 全面解析 Nginx 动静分离。 一、动静分离原理 1. 什么是动静分离? 动态资源(动):需要经过后台程序处理或数据库交互生成的内容,通常是非静态的。例如: /api/userinfo /search?keyword=abc *.jsp, *.php, *.do


前端基础:从0到1制作简单网页(三)
<但凡.2025/10/27

HTML容器元素分类 1. 通用容器 <div> - 通用块级容器 <span> - 通用内联容器(处理行内内容) 2. 语义化容器(HTML5新增) <header> - 页眉或章节头部 <footer> - 页脚或章节尾部 <main> - 文档主要内容 <section> - 文档章节 <article> - 独立内容块(如博客文章) <aside> - 侧边栏或相关内容 <nav> - 导航链接区域 <figure> -


从海量文档到精准数据:文档抽取技术驱动金融财税决策新范式
智能图像文字识别OCR2025/10/24

在金融与财税这个由海量文档驱动的领域中,效率与准确性是生命线。从繁复的财务报表、五花八门的发票,到冗长的合同与合规文件,传统的人工处理方式不仅成本高昂、效率低下,还极易出错。随着人工智能技术的成熟,文档抽取技术正成为解决这些痛点的关键利器,驱动着整个行业向智能化、自动化加速转型。 文档抽取技术简介及其工作原理 文档抽取技术是自然语言处理(NLP)和计算机视觉(CV)的一个交叉分支,其核心目标是从非结构化或半结构化的文档(如PDF、图片、扫描件)中,自动识别、定位并提取出特定的关键信息,并将其


金庸群侠传2攻略
funny-flash2025/10/22

金庸群侠传2攻略 金庸群侠传2加强版-免插件在线玩 本文为转载,原文地址:https://www.bilibili.com/opus/654149447904657428 一、前期衡阳城(游戏起始) 江湖称号:江湖小混混  (修炼《吐纳心法》至第5重时悟《吐纳术》)  1.田伯光欺负小尼姑任务。两次选帮助者,可提升一定属性。 2.客栈二楼,选1.上前搭讪(是否与他结拜影响到华山任务)  →选1 我虽非正人君子,但还知道廉耻!→得九转熊蛇丸  →选2 田兄在上,受小弟一拜!  →选1 阻止田伯光杀


每周读书与学习->JMeter主要元件详细介绍(一)配置元件
张永清-老清2025/10/21

每周读书与学习是由清华大学出版社出版的《JMeter核心技术、性能测试与性能分析》一书的作者推出,分享作者多年的IT从业经历,希望对很多计算机科学技术IT类专业毕业生以及IT从业者有所帮助。 在前面的学习中,我们已经讲到在Jmeter中配置元件主要用于完成性能测试中一些常见配置信息的配置,在前面的章节学习中,大家或许已经对配置元件的使用和作用有了一个初步的了解,在本章节学习中,我们将对一些常见的配置元件进行详细的介绍。 1、配置元件 1.1.CSV数据文件设置 如下图所示,CSV 数据文


AWS云基础设施可观测性完整指南
ivwdcwso2025/10/20

引言 在现代云原生架构中,可观测性已成为确保系统稳定性、性能和可靠性的关键要素。本文将深入探讨如何在AWS云环境中构建完整的可观测性体系,涵盖监控、日志、追踪和告警的最佳实践。 可观测性三大支柱 1. 指标监控 (Metrics) 指标是系统性能的数值化表示,提供系统健康状况的量化视图。 核心指标类型: 基础设施指标: CPU、内存、磁盘、网络 应用指标: 响应时间、吞吐量、错误率 业务指标: 用户活跃度、交易量、转化率 2. 日志记录 (Logs) 日志提供系


为何一个系统上线要经过N轮测试?带你看懂企业级发布体系
G探险者2025/10/19

大家好,我是G探险者! 在 IT 行业中,一个系统从开发完成到最终上线生产,并不是一蹴而就的过程。 你可能听说过这样的说法:“代码要经过 N 轮测试才能上线。” 从开发环境(DEV)到系统集成测试(SIT),再到用户验收测试(UAT),最后部署到生产环境(PROD),每一步都在为最终的稳定上线保驾护航。 这种多环境、多阶段的发布流程,表面上看似繁琐,但它背后承载的是风险控制、质量保障与团队协作的体系化思想。 如果缺乏这些环节,哪怕一个小小的配置错误、接口不兼容、性能瓶颈,都可能在生产环境引发严重


注入“侨动力” 锻造“湘非链”
hg01182025/10/17

2025年非洲侨团侨领侨商湖南行首场活动在长沙举办。 红网时刻新闻记者 聂伊岑 秦楼 卢欣 陈啸鼎 长沙报道 汇聚侨智侨力,深化湘非合作。 9月27日至30日,2025年非洲侨团侨领侨商湖南行活动在长沙、邵阳两地举办。 长沙市雨花区8个优质项目牵手非洲;15个湘非合作项目落地湖南湘江新区;邵阳海外订单纷至沓来;10位“海外招商大使”成为湖南与非洲之间最活跃的“经贸使者”。 本次湖南行成功将双方的深厚友谊与共同愿景转化为了实实在在的合作成果。 回顾4天的活动,不难发现,湖南与非洲的“朋


Redis(64)Redis的Lua脚本有哪些常见场景?
Victor3562025/10/16

Redis 的 Lua 脚本可以极大提升操作的原子性和效率,特别适用于需要多个 Redis 命令组合执行的场景。以下是一些常见的使用场景,并结合代码进行详细说明。 1. 分布式锁 Redis 的 Lua 脚本常用于实现分布式锁,以确保多个客户端在并发访问时的互斥性。 示例:分布式锁的获取与释放 -- 获取锁 local lock_key = KEYS[1] local lock_value = ARGV[1] local ttl = tonumber(ARGV[2]) if redis.cal

首页编辑器站点地图

本站内容在 CC BY-SA 4.0 协议下发布

Copyright © 2025 聚合阅读