Hubbry Logo
Cd (command)Cd (command)Main
Open search
Cd (command)
Community hub
Cd (command)
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Cd (command)
Cd (command)
from Wikipedia
cd / chdir
DevelopersAT&T Bell Laboratories, MetaComCo, Microsoft, IBM, DR, Novell, HP, JP Software, ReactOS Contributors
Operating systemUnix, Unix-like, V, DOS, MSX-DOS, FlexOS, OS/2, TRIPOS, Windows, MPE/iX, Plan 9, Inferno, ReactOS, KolibriOS, SymbOS
PlatformCross-platform
TypeCommand

cd is a shell command that changes the working directory. It is available in many shells and other applications that maintain a working directory. In some contexts, the command can perform actions other than change directory. Some environments provide the change directory feature via a different command name such as chdir.

Implementations

[edit]

Generally, a computer system that provides access to a hierarchical file system, provides a change directory command to set the working directory. As this applies to most operating system shells, most support a change directory command, including Unix and Unix-like (i.e. Linux) shells, and Microsoft shells including Command Prompt and PowerShell.

Other operating systems with shells supporting the command include OS/2,[1] TRIPOS,[2] AmigaOS[3] (where the command is implied for an input path), ReactOS,[4] DOSBox, and UEFI.[5]

Unlike many shell commands that are implemented as separate applications, change directory is often built-in to the shell because it affects the state of the shell whereas other commands modify system state outside the shell. If the command was implemented as a separate application, then the child process would need to modify state in the parent process, but this is often prevented for safety. The command is built-in for most Unix shells (Bourne, tcsh, Bash, etc.), Windows Command Prompt and PowerShell, and MS-DOS COMMAND.COM.

In a shell, the change directory command is typically implemented via a system call which on Unix and Unix-like systems is typically POSIX chdir() and on Windows is in the Windows API.

The command is also provided in many programs other than shells. In the File Transfer Protocol, the control stream command is CWD, but the functionality is available as cd in most command-line clients and some also provide lcd for changing the local working directory vs. the remote setting. The numerical computing environments MATLAB and GNU Octave include a change directory command as cd.[10][11]

Use

[edit]

Use of the command varies by context, but there are widespread similarities among variants. The examples below, mostly apply to Unix and Unix-like shells, PowerShell and Command Prompt.

To separate the directory names of a path, a program imposes command-line syntax such as a delimiting text between names – which varies by program. In particular, Unix and Unix-like shells use a forward slash /, Command Prompt uses backslash \ and PowerShell supports either. For simplicity, paths are shown with forward slashes here.

Commonly, a dot is short-hand notation for the working directory and two dots is short-hand for its parent. For example, given working directory /user/bin/tmp, . refers to it and .. refers to /user/bin. The parent notation is often used to form a relative path that specifies a path that is both up and down the hierarchy. For example: starting with /usr/bin/tmp, cd ../../local specifies path /usr/local.

Common

[edit]

Features that are commonly found for any change directory command:

  • cd path/to/dir For a relative path (no leading slash), the path is appended to the working directory path, moving the context deeper into the directory tree hierarchy; for example, if the working directory is /usr, then cd bin changes the working directory to /usr/bin
  • cd /path/to/dir For an absolute path (leading slash), the working directory is replaced with the specified path; for example, cd /bin sets the working directory to /bin
  • cd .. Moves the directory tree context up one directory; for example, starting at /usr/bin/tmp, cd .. changes the working directory to /usr/bin
  • cd . Does not change the working directory but is useful to recover after a directory is recreated by another process
  • cd With no arguments, the command changes the working directory to the user's home directory; exception: Command Prompt reports the working directory path

Unix shells

[edit]

Unix-based shells and PowerShell generally share these features:

  • cd ~ Changes the working directory to user's home directory
  • cd ~username Changes the working directory to the specified user's home directory
  • cd - Changes the working directory to the previous directory; for example, starting at /usr/bin/tmp, executing cd /etc followed by cd - returns to /usr/bin/tmp, which enables toggling between two directories without pushd and popd

Legacy Microsoft shells

[edit]

DOS maintains separate working directories for each lettered drive, and also has the concept of a current working drive. The cd command can be used to change the working directory of the working drive or another lettered drive. Typing the drive letter as a command on its own changes the working drive, e.g. C:; alternatively, cd with the /d switch may be used to change the working drive and that drive's working directory in one step. Modern versions of Windows simulate this behaviour for backwards compatibility under CMD.EXE.[12]

Example

[edit]
Section of a Unix filesystem showing a user's home directory (represented as ~) with a file and three subdirectories.

Starting with working directory set to the user's home (~), command ls followed by cd games might produce the following:

user@wikipedia:~$ ls
workreports games encyclopedia text.txt
user@wikipedia:~$ cd games
user@wikipedia:~/games$

A similar session in Command Prompt might look like:

C:\> dir
workreports        <DIR>       Wed Oct 9th   9:01
games              <DIR>       Tue Oct 8th  14:32
encyclopedia       <DIR>       Mon Oct 1st  10:05
text        txt           1903 Thu Oct10th  12:43
C:\> cd games
C:\games>

See also

[edit]

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The cd command is a special built-in shell utility in POSIX-compliant systems, including Unix-like operating systems, designed to change the working directory of the current shell execution environment. It originated as part of the Bourne shell, introduced with Version 7 Unix in 1979, and remains a fundamental navigation tool for file systems in modern shells such as sh, bash, and zsh. The command processes directory paths either logically (default, treating symbolic links after resolving parent directories) or physically (resolving symbolic links during traversal), updating environment variables like PWD and OLDPWD upon success. In its standard form, cd accepts an optional directory argument, which can be an absolute or relative path; if no argument is provided, it defaults to the value of the HOME , or to an implementation-defined directory if HOME is unset. Special handling includes the operand -, which changes to the previous stored in OLDPWD and prints its pathname, facilitating quick toggling between directories. Relative paths not starting with / may be searched via the CDPATH , a colon-separated list of directories, to support path completion. Options include -L for logical path resolution (the default) and -P for physical resolution, ensuring portability across systems while handling symbolic links and permissions errors with appropriate exit statuses. Extensions in specific shells, such as Bash, add options like -@ to display extended attributes and -e (with -P) to check resolvability of the new directory, but core functionality adheres to for broad compatibility. The command returns 0 on success or a non-zero value if the directory is inaccessible or invalid, making it integral to scripting and interactive use without spawning external processes.

Introduction

Purpose and Functionality

The cd command, short for "change directory," is a fundamental utility in command-line interfaces designed to switch the current within hierarchical . It enables users to navigate the structure by updating the shell's execution environment to a specified directory, thereby facilitating access to files, subdirectories, and executables without relying on graphical navigation tools. At its core, modifies the shell's , which serves as the default location for interpreting relative paths in subsequent commands. This change affects only the current shell session and its child processes, ensuring that operations like file listings or script executions occur in the intended context. By altering this —typically represented as cd streamlines workflow in text-based environments where efficient directory traversal is essential. The command supports paths that are either relative to the current directory (e.g., using dot notation for the present location or dot-dot for the ) or absolute (starting from the of the ), allowing precise control over . This dual-path capability ensures flexibility in hierarchical structures, where each invocation resets the reference point for all future relative operations within the shell. Since its introduction in early Unix systems in the , cd has become ubiquitous in text-based interfaces, remaining indispensable for management in resource-constrained or server environments lacking graphical interfaces.

Historical Context

The concept of changing the originated in the operating system, developed in the 1960s by MIT, , and , where commands like change_wdir (abbreviated as cwd) and change_default_wdir (cdwd) allowed users to alter their current directory in a . This design influenced the file system architecture of Unix, created by and at in the early 1970s after their withdrawal from the project; Unix adopted and simplified directory navigation to support efficient and user processes. The cd command first appeared in Unix Version 1, released in November 1971, initially as the chdir and shell command for changing the current , integrated as a built-in to avoid the overhead of forking external processes. In the of early Unix, chdir handled directory changes directly, reflecting the system's emphasis on simplicity and portability across PDP-11 hardware. The command evolved with the introduction of the in 1977 by at , which standardized cd as a built-in shell command, supporting path arguments and defaulting to the user's , thereby enhancing scripting and interactive use in . This version influenced subsequent shells like the and Korn shell, leading to its formal standardization in POSIX.1-1988 (IEEE Std 1003.1-1988), which defined cd with specified behavior for path resolution and error handling to ensure portability across systems. In parallel, the cd command entered non-Unix environments with Microsoft's 2.0 in 1983, where it was introduced as the CHDIR internal command with cd as an alias, to support directory navigation in the new hierarchical file system and improve compatibility with Unix conventions. This integration carried forward into in 1993, where the cmd.exe shell retained cd (and chdir) within its POSIX-compatible command environment, bridging legacy DOS functionality with the NT kernel's protected-mode architecture.

Syntax and Parameters

Basic Syntax

The cd command, short for "change directory," uses the fundamental syntax cd [directory], where the optional directory argument specifies the target path to which the current is changed. If no directory is provided, the command defaults to switching to the user's . Directory paths in the cd command can be absolute or relative. Absolute paths specify the full location from the root of the filesystem, starting with a forward slash (/) in systems or a drive letter followed by a colon and optional (e.g., C:\) in Windows environments. Relative paths, by contrast, are interpreted with respect to the current and may include dot notation such as ./ to denote the current directory or ../ to move to the directory (e.g., ./subdir or ../parent). In systems, special path shorthands enhance usability: the (~) expands to the user's via shell tilde expansion, allowing cd ~ as an equivalent to omitting the directory argument. Additionally, cd - toggles to the previous by referencing the shell variable OLDPWD. The cd command is implemented as a shell built-in in both environments and Windows Command Prompt, rather than an external executable, to directly and efficiently update the shell process's without forking a subprocess.

Common Options

The cd command supports several options that modify its behavior, with the most portable ones defined in the standard. The -L option forces logical handling of paths, where symbolic links are followed when resolving .. components after initial processing, which is the default behavior in many implementations if no option is specified. Conversely, the -P option enables physical path resolution, where symbolic links are resolved to their targets before processing .. components, preventing traversal through symlinks. If both -L and -P are provided, the last one takes precedence. In environments such as Bash, additional options extend functionality beyond the baseline. The - switches to the previous stored in the OLDPWD and prints the new directory path upon success. The ~user form changes to the of the specified user, expanding to the full path via the password database. Bash also supports -- to signal the end of options, allowing directory names beginning with - to be treated as arguments rather than flags. Options vary across implementations, reflecting environment-specific extensions while maintaining core compatibility. In Windows Command Prompt, the /d option changes both the current directory and the default drive when the target path is on a different drive from the current one. Regardless of the implementation, the cd command returns a non-zero if the directory change fails, such as when the specified path does not exist or access is denied due to permissions; otherwise, it returns 0 on success, leaving the unchanged in case of error.

Usage in Different Environments

Unix-like Shells

In Unix-like shells such as sh, bash, and zsh, the cd command serves as a built-in utility to change the current working directory, with standardized behavior for handling symbolic links and path expansions. By default, without options, cd follows the logical path resolution specified by the -L flag, which processes symbolic links after handling .. components in the path, allowing traversal through symlinks to reach the target directory. Conversely, the -P option enforces physical path resolution, resolving all symbolic links during the directory traversal before processing .., which prevents following symlinks and ensures a canonical path without indirection. Additionally, the tilde (~) in path arguments expands to the value of the $HOME environment variable, enabling shorthand navigation to the user's home directory, such as cd ~ or cd ~user for another user's home. Bash and zsh extend the core functionality with the CDPATH environment variable, a colon-separated list of directories that the shell searches sequentially when the provided directory name does not begin with a slash or contain a dot-dot component, facilitating quicker navigation to subdirectories without full paths. For enhanced directory management, both shells provide pushd and popd as wrappers around cd, maintaining a directory stack: pushd changes to the specified directory while pushing the current one onto the stack, and popd removes the top entry from the stack and changes to it, with dirs displaying the stack contents. These features promote efficient bookmarking and alternation between directories in interactive sessions. In the (csh) and its enhanced variant , cd is implemented as a built-in command aliased to chdir, providing identical functionality for changing directories while supporting the shell's cdpath variable for path searching akin to other shells. A distinctive feature is the integration of history substitution using the (!), allowing paths in cd arguments to reference and modify previous command history, such as cd !#:1:h to navigate to the parent directory of the first argument from the current command line. Regardless of the specific shell, successful execution of cd updates the $PWD to the absolute pathname of the new and sets $OLDPWD to the previous working directory's absolute pathname, enabling features like cd - to return to the prior location. If the target directory does not exist or is inaccessible, cd prints a diagnostic message to (e.g., "No such file or directory") and exits with a non-zero status, typically 1, leaving the current unchanged.

DOS and Windows Command Prompt

In and the Windows Command Prompt (), the cd command, short for "change directory," is used to display or modify the current on a specified drive. It was introduced with 2.0 in 1983 as a core internal command for navigating the in early PC-compatible environments. The command shares the same functionality as its synonym chdir, which was the original name but has since been aliased to cd for brevity. The basic syntax is cd [drive:][path], where the optional drive: specifies a disk drive (e.g., C:) and path denotes the target directory, using backslashes (\) as path separators in line with DOS conventions. When invoked without parameters, cd displays the current drive and directory, such as C:\Users\Example. Specifying only a drive letter, like cd D:, shows the current directory on that drive without changing the active drive. A key aspect of its behavior is that each drive maintains an independent current directory; executing cd C:\Windows sets the current directory on drive C: but does not switch the active drive from, say, D: to C: unless explicitly handled. In pure MS-DOS environments, switching drives required simply typing the drive letter followed by a colon (e.g., D:), which updated both the active drive and its current directory. However, in Windows NT 4.0 and later versions of cmd.exe, the /d switch was added to cd to enable changing both the directory and the drive in a single command, as in cd /d C:\Windows. Without /d, the command only updates the target drive's directory pointer, leaving the prompt on the original drive—a design choice rooted in DOS compatibility to avoid disrupting batch scripts or applications assuming per-drive independence. Beginning with , which introduced support for long filenames (up to 255 characters) beyond the traditional 8.3 format, paths containing spaces or special characters must be enclosed in double quotes for cd to parse them correctly, such as cd "C:\Program Files". If an invalid path is provided, cd returns the error message "The system cannot find the path specified," indicating the directory does not exist or is inaccessible due to permissions or syntax issues. For navigation, cd .. moves up one level to the parent directory, while cd \ jumps to the root of the current drive. These features ensure compatibility with legacy MS-DOS batch files and scripts, where cd remains a fundamental tool for file system traversal despite the evolution toward graphical interfaces.

PowerShell and Modern Shells

In PowerShell, the cd command is an alias for the Set-Location cmdlet, which changes the current working location to a specified path, such as a file system directory, registry key, or other provider-backed store. This cmdlet supports navigation across various PowerShell providers, including the FileSystem provider for directories (e.g., cd C:\Users) and the Registry provider for hives (e.g., cd HKLM:\SOFTWARE), enabling unified access to diverse data stores without switching contexts. The -PassThru parameter allows Set-Location to return a PathInfo object representing the new location, facilitating object-oriented scripting where the output can be piped to other cmdlets for further processing, such as querying properties or integrating into workflows. PowerShell Core 6.0 and later versions (including 7 and later), introduced as part of the cross-platform PowerShell Core initiative starting with previews in 2016 and general availability in 2018, unify behavior across Windows, , and macOS by leveraging .NET Core, ensuring consistent cd functionality like defaulting to the $HOME when using cd ~ or omitting a path. This cross-platform design maintains the while adapting paths appropriately, such as treating Linux directories natively without Windows-specific drive letters. In environments like Git Bash on Windows, the cd command emulates behavior within a environment, automatically converting Windows paths (e.g., C:\Program Files) to Unix-style equivalents (e.g., /c/Program Files) for seamless navigation between native and emulated file systems. Similarly, in (WSL), cd operates as a standard Unix command but accesses Windows files via mounted paths under /mnt/, such as cd /mnt/c/Users, requiring manual or tool-assisted conversion for direct Windows path usage. Modern shells like extend cd with enhanced interactivity, including rich tab completion for paths and commands, which suggests completions based on and context as the user types. 's cd wrapper also maintains a of the 25 most recently visited directories in universal variables $dirprev and $dirnext, allowing backward and forward navigation with cd - or cd + for efficient traversal without retyping full paths.

Examples

Basic Navigation

The cd command facilitates fundamental directory navigation by altering the shell's current , enabling users to move through the hierarchy efficiently. In systems, specifying an absolute path with cd directs the shell to that location from the , regardless of the starting point; for instance, executing cd /home/user from any directory changes the to the user's home folder, after which the shell prompt typically updates to reflect the new location, such as [user@hostname ~]$, confirming the change without additional output on success. Relative paths allow navigation within the current directory structure without full paths. To enter a subdirectory named "documents," the command cd documents shifts the working directory downward; conversely, cd .. moves up one level to the parent directory, simplifying traversal of nested folders. Special cases include using - to switch to the previous working directory: executing cd - changes to the value of OLDPWD and prints its pathname (e.g., /previous/dir), facilitating quick toggling between directories. These operations are immediate and silent upon success (except for cd -), with the prompt's path indicator—often customized in shells like Bash to show the current directory—serving as visual confirmation of the navigation. When invoked without arguments, cd behaves differently across environments: in Unix-like shells, it defaults to the user's (symbolized by ~), executing cd ~ implicitly to return to that base location. In contrast, the Windows Command Prompt displays the current directory path without changing it, functioning akin to a query rather than a navigation action. In Windows environments, switching drives alongside directories requires the /d option, as cd alone does not alter the active drive. For example, cd /d D:\projects changes both the drive to D: and the directory to \projects, updating the prompt to D:\projects> to indicate the transition. This ensures comprehensive navigation in multi-drive systems, where standard cd would only adjust the path on the current drive.

Advanced Examples

In scripting scenarios, the cd command is often used conditionally to ensure successful directory changes before proceeding with subsequent operations. For example, the following Bash script snippet verifies the change to /tmp before listing its contents:

bash

if cd /tmp; then ls fi

if cd /tmp; then ls fi

This approach leverages the cd builtin's return status, which is zero on success and non-zero on failure, allowing the script to handle errors gracefully without halting execution unless explicitly coded to do so. The directory stack provides a mechanism for temporarily saving and restoring working directories, integrating seamlessly with . The builtin adds a directory to the stack and changes to it using internally, while removes the top entry and changes back. Consider this sequence in Bash:

bash

pushd /var # Now in /var; perform operations here popd # Returns to previous directory

pushd /var # Now in /var; perform operations here popd # Returns to previous directory

If fails during these operations (e.g., due to permissions), and return non-zero, preventing inconsistent stack states. Using variables enhances flexibility, particularly for paths with spaces or dynamic locations. In Bash, expand a variable safely with quotes:

bash

homedir=$[HOME](/page/Home) cd "$homedir/docs"

homedir=$[HOME](/page/Home) cd "$homedir/docs"

This prevents word-splitting issues, ensuring the full path is treated as a single argument. The cd command updates the [PWD](/page/Pwd) environment variable to the new absolute path upon success. For robust scripting, enable the set -e option at the script's start to exit immediately if cd or any command fails. An example error case is attempting to change to a non-existent directory:

bash

cd nonexistent

cd nonexistent

This outputs "bash: cd: nonexistent: No such file or directory" and returns non-zero, triggering an exit under set -e. With the -P option combined with -e, Bash returns non-zero even after a successful change if the physical current directory cannot be determined afterward. To verify a directory change, combine cd with the pwd builtin, which prints the current working directory:

bash

cd .. pwd

cd .. pwd

This confirms the new location, outputting the absolute path of the parent directory, and relies on cd updating PWD correctly.

Implementations and Standards

POSIX Specification

The cd utility in POSIX is a shell built-in command that changes the working (current) directory of the shell execution environment to the specified directory or, if none is specified, to the user's home directory. It is defined in the Shell and Utilities volume of the POSIX.1 standard, which ensures portability across conforming Unix-like systems by specifying behavior for path resolution, symbolic link handling, and environment interactions. The specification emphasizes minimalism to promote interoperability, mandating support for absolute and relative paths using the forward slash (/) as the directory separator, while tilde (~) expansion for home directories is handled by the shell rather than cd itself. The synopsis of the command is cd [-L|-P] [directory] or cd -, where directory is an optional absolute or relative pathname. If no directory operand is provided, cd changes to the value of the HOME environment variable. The -L option (default) performs logical path searches, following symbolic links during resolution except for dot (.) and dot-dot (..) components, while -P enables physical path handling by resolving all symbolic links and not following them for dot or dot-dot. The special operand - changes the working directory to the previous one (stored in OLDPWD) and writes that directory's pathname to standard output. Upon successful execution, cd updates the PWD environment variable to reflect the new working directory, using either logical or physical resolution based on the option used. The CDPATH environment variable, if set, provides a colon-separated list of directories to search for relative pathnames, aiding in non-absolute navigation. POSIX requires cd to fail and return an greater than zero if the target directory does not exist, is not a directory, or lacks appropriate search permissions for the user or intermediate path components. It does not support directory stack operations like pushd or popd, which are non-standard extensions in specific shells. The command produces no output to standard output except when using the - or when CDPATH search succeeds for a relative path (in which case it prints the absolute pathname used). began with the utilities in IEEE Std 1003.2-1992 (derived from earlier Unix practices), with integration into the core POSIX.1 standard in IEEE Std 1003.1-2001 and refinements in subsequent revisions, including IEEE Std 1003.1-2008, which clarified symlink handling and behaviors for better portability, and later revisions up to IEEE Std 1003.1-2024.

Microsoft Implementations

In Windows implementations, the cd command and its underlying functionality are provided through the , specifically the SetCurrentDirectory function exported from kernel32.dll. This changes the current directory for the calling , enabling applications and shells to navigate the . The function accepts a path string and returns a indicating success, with the current directory consisting of a drive designator (such as a letter followed by a colon) and a path component. In the traditional Command Prompt (cmd.exe), the cd command (aliased as chdir) displays or changes the current directory, supporting the /d switch to simultaneously change the current drive and directory when navigating to a path on a different volume. For example, cd /d D:\folder switches both the drive and directory. However, cd in cmd.exe does not support Universal Naming Convention (UNC) paths (e.g., \\server\share) as the current working directory, resulting in an error; instead, the pushd command is used to temporarily map and navigate UNC paths. With command extensions enabled (the default), cd handles paths with spaces without requiring quotes and preserves the case of drive letters as stored on disk. PowerShell's equivalent, the Set-Location cmdlet (with cd as an alias), leverages the .NET Framework's System.IO.Directory.SetCurrentDirectory method to modify the working location, supporting a broader range of providers beyond the file system, such as the registry or certificates. Unlike cmd.exe, Set-Location fully supports UNC paths directly, allowing navigation to network shares like Set-Location \\server\share without additional mapping. This integration provides a more flexible, object-oriented approach to directory changes within PowerShell's pipeline model. Starting with , has enhanced compatibility with behaviors through the (WSL), where cd operates as a standard POSIX-compliant command within distributions running on Windows. Additionally, long path support (exceeding the traditional 260-character limit) is enabled via the \\?\ prefix for local paths or \\?\UNC\ for network paths, configurable through or registry settings, allowing SetCurrentDirectory and shell commands to handle extended file paths in modern applications. A key distinction in Windows is the drive-relative nature of current directories: each maintains a separate current directory per drive, rather than a single global one, so changing to a path on drive D: updates only that drive's pointer while preserving others. This per-process, per-drive model ensures that relative paths resolve correctly based on the most recent activity on each volume. Native Windows implementations are proprietary and do not fully comply with standards for cd, lacking features like handling or case-sensitive navigation by default. Partial compliance is achieved through environments like , which emulates a shell with a cd via its DLL layer, or /MSYS2, which provides a -compatible bash shell for development tools. These layers translate Windows paths to semantics but rely on the underlying Win32 for core operations.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.