Recent from talks
Nothing was collected or created yet.
Cd (command)
View on Wikipedia| cd / chdir | |
|---|---|
| Developers | AT&T Bell Laboratories, MetaComCo, Microsoft, IBM, DR, Novell, HP, JP Software, ReactOS Contributors |
| Operating system | Unix, Unix-like, V, DOS, MSX-DOS, FlexOS, OS/2, TRIPOS, Windows, MPE/iX, Plan 9, Inferno, ReactOS, KolibriOS, SymbOS |
| Platform | Cross-platform |
| Type | Command |
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]
- On MS-DOS, the command is available in version 2 and later[6]
- DR DOS 6.0 includes the command as both
cdandchdir[7] - On HP MPE/iX the command is
chdir[8] - On OpenVOS, the command is
change_current_dir[9]
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/dirFor 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, thencd binchanges the working directory to/usr/bincd /path/to/dirFor an absolute path (leading slash), the working directory is replaced with the specified path; for example,cd /binsets the working directory to/bincd ..Moves the directory tree context up one directory; for example, starting at/usr/bin/tmp,cd ..changes the working directory to/usr/bincd .Does not change the working directory but is useful to recover after a directory is recreated by another processcdWith 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 directorycd ~usernameChanges the working directory to the specified user's home directorycd -Changes the working directory to the previous directory; for example, starting at/usr/bin/tmp, executingcd /etcfollowed bycd -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]
~) 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]- Directory structure – Hierarchical structure of a computer's file system
- chroot – Shell command and system call that changes the apparent root directory
- List of command-line interpreters
- pushd and popd – Shell commands to save and restore the working directory
- pwd – Shell command that reports the working directory
References
[edit]- ^ "JaTomes Help – OS/2 Commands". www.jatomes.com. Archived from the original on 2019-04-14. Retrieved 2019-08-11.
- ^ "Introduction to Tripos" (PDF). Archived (PDF) from the original on 2020-10-21. Retrieved 2020-05-01.
- ^ Rügheimer, Hannes; Spanik, Christian (May 1, 1988). AmigaDOS quick reference. Grand Rapids, Mi : Abacus. ISBN 9781557550491 – via Internet Archive.
- ^ "Reactos/reactos". GitHub. 3 January 2022. Archived from the original on 31 March 2022. Retrieved 11 August 2019.
- ^ "EFI Shells and Scripting". Intel. Archived from the original on 2013-09-27. Retrieved 2013-09-25.
- ^ Wolverton, Van (2003). Running MS-DOS Version 6.22 (20th Anniversary Edition), 6th Revised edition. Microsoft Press. ISBN 0-7356-1812-7.
- ^ "DR DOS 6.0 User Guide Optimisation and Configuration Tips" (PDF). Archived from the original (PDF) on 2019-09-30. Retrieved 2019-08-13.
- ^ "MPE/iX Command Reference Manual" (PDF). Archived from the original (PDF) on 2018-10-21. Retrieved 2018-10-21.
- ^ "OpenVOS Commands Reference Manual" (PDF). stratadoc.stratus.com. Archived (PDF) from the original on 2019-09-22. Retrieved 2020-09-12.
- ^ "Change current folder – MATLAB cd". www.mathworks.com.
- ^ "Function Reference: cd". octave.sourceforge.io. Archived from the original on 2019-04-06. Retrieved 2019-04-06.
- ^ "October 11, 2010". The Old New Thing. Archived from the original on October 29, 2020. Retrieved September 12, 2020.
Further reading
[edit]- Wolverton, Van (1990). MS-DOS Commands: Microsoft Quick Reference, 4th Revised edition. Microsoft Press. ISBN 978-1-55615-289-4.
- John Paul Mueller (2007). Windows Administration at the Command Line for Windows Vista, Windows 2003, Windows XP, and Windows 2000. John Wiley & Sons. ISBN 978-0-470-16579-9.
- Barrett, Daniel J. (2012). Macintosh Terminal Pocket Guide: Take Command of Your Mac. O'Reilly. ISBN 978-1-4493-2898-6.
External links
[edit]- Windows XP > Command-line reference A-Z > Chdir (Cd) from Microsoft TechNet
- : change the working directory – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Group
Cd (command)
View on Grokipediacd 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.[1] 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.[2] 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.[1]
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 environment variable, or to an implementation-defined directory if HOME is unset.[1] Special handling includes the operand -, which changes to the previous working directory stored in OLDPWD and prints its pathname, facilitating quick toggling between directories.[1] Relative paths not starting with / may be searched via the CDPATH environment variable, a colon-separated list of directories, to support path completion.[1] 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.[1]
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 POSIX for broad compatibility.[3] 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.[1]
Introduction
Purpose and Functionality
Thecd command, short for "change directory," is a fundamental utility in command-line interfaces designed to switch the current working directory within hierarchical file systems. It enables users to navigate the file system 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.[1]
At its core, cd modifies the shell's working directory, 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 environment variable—typically represented as PWD—cd streamlines workflow in text-based environments where efficient directory traversal is essential.[1][4]
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 parent) or absolute (starting from the root of the file system), allowing precise control over navigation. This dual-path capability ensures flexibility in hierarchical structures, where each invocation resets the reference point for all future relative operations within the shell.[1]
Since its introduction in early Unix systems in the 1970s, cd has become ubiquitous in text-based interfaces, remaining indispensable for file system management in resource-constrained or server environments lacking graphical interfaces.[5]
Historical Context
The concept of changing the working directory originated in the Multics operating system, developed in the 1960s by MIT, Bell Labs, and General Electric, where commands likechange_wdir (abbreviated as cwd) and change_default_wdir (cdwd) allowed users to alter their current directory in a hierarchical file system.[6] This design influenced the file system architecture of Unix, created by Ken Thompson and Dennis Ritchie at Bell Labs in the early 1970s after their withdrawal from the Multics project; Unix adopted and simplified directory navigation to support efficient time-sharing and user processes.
The cd command first appeared in Unix Version 1, released in November 1971, initially as the chdir system call and shell command for changing the current working directory, integrated as a built-in to avoid the overhead of forking external processes.[7] In the Thompson shell of early Unix, chdir handled directory changes directly, reflecting the system's emphasis on simplicity and portability across PDP-11 hardware.[8]
The command evolved with the introduction of the Bourne shell in 1977 by Stephen R. Bourne at Bell Labs, which standardized cd as a built-in shell command, supporting path arguments and defaulting to the user's home directory, thereby enhancing scripting and interactive use in Version 7 Unix.[9] This version influenced subsequent shells like the C shell 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 Unix-like systems.[10]
In parallel, the cd command entered non-Unix environments with Microsoft's MS-DOS 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 FAT file system and improve compatibility with Unix conventions.[11] This integration carried forward into Windows NT 3.1 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
Thecd command, short for "change directory," uses the fundamental syntax cd [directory], where the optional directory argument specifies the target path to which the current working directory is changed.[1][12] If no directory is provided, the command defaults to switching to the user's home directory.[1]
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 Unix-like systems or a drive letter followed by a colon and optional backslash (e.g., C:\) in Windows environments.[1][12] Relative paths, by contrast, are interpreted with respect to the current working directory and may include dot notation such as ./ to denote the current directory or ../ to move to the parent directory (e.g., ./subdir or ../parent).[1]
In Unix-like systems, special path shorthands enhance usability: the tilde (~) expands to the user's home directory via shell tilde expansion, allowing cd ~ as an equivalent to omitting the directory argument.[13] Additionally, cd - toggles to the previous working directory by referencing the shell variable OLDPWD.[1]
The cd command is implemented as a shell built-in in both Unix-like environments and Windows Command Prompt, rather than an external executable, to directly and efficiently update the shell process's working directory without forking a subprocess.[1][12]
Common Options
Thecd command supports several options that modify its behavior, with the most portable ones defined in the POSIX 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.[1] Conversely, the -P option enables physical path resolution, where symbolic links are resolved to their targets before processing .. components, preventing traversal through symlinks.[1] If both -L and -P are provided, the last one takes precedence.[1]
In Unix-like environments such as Bash, additional options extend functionality beyond the POSIX baseline. The - operand switches to the previous working directory stored in the OLDPWD environment variable and prints the new directory path upon success.[14] The ~user form changes to the home directory of the specified user, expanding to the full path via the password database.[14] Bash also supports -- to signal the end of options, allowing directory names beginning with - to be treated as arguments rather than flags.[14]
Options vary across implementations, reflecting environment-specific extensions while maintaining core POSIX 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.[12]
Regardless of the implementation, the cd command returns a non-zero exit status 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 working directory unchanged in case of error.[1]
Usage in Different Environments
Unix-like Shells
In Unix-like shells such as sh, bash, and zsh, thecd 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.[1][14][15]
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.[14][16]
In the C shell (csh) and its enhanced variant tcsh, 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 exclamation mark (!), 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.[17]
Regardless of the specific shell, successful execution of cd updates the $PWD environment variable to the absolute pathname of the new working directory 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 standard error (e.g., "No such file or directory") and exits with a non-zero status, typically 1, leaving the current working directory unchanged.[1][18]
DOS and Windows Command Prompt
In MS-DOS and the Windows Command Prompt (cmd.exe), thecd command, short for "change directory," is used to display or modify the current working directory on a specified drive.[12] It was introduced with MS-DOS 2.0 in 1983 as a core internal command for navigating the file system in early IBM PC-compatible environments.[19] The command shares the same functionality as its synonym chdir, which was the original name but has since been aliased to cd for brevity.[20]
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.[12] When invoked without parameters, cd displays the current drive and directory, such as C:\Users\Example.[12] Specifying only a drive letter, like cd D:, shows the current directory on that drive without changing the active drive.[12] 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.[12]
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.[21] 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.[12] 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.[12]
Beginning with Windows 95, 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".[22] 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.[23]
For navigation, cd .. moves up one level to the parent directory, while cd \ jumps to the root of the current drive.[12] 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.[12]
PowerShell and Modern Shells
In PowerShell, thecd 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.[24] 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.[25] 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.[24]
PowerShell Core 6.0 and later versions (including PowerShell 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, Linux, and macOS by leveraging .NET Core, ensuring consistent cd functionality like defaulting to the $HOME environment variable when using cd ~ or omitting a path.[26] This cross-platform design maintains the provider model while adapting paths appropriately, such as treating Linux directories natively without Windows-specific drive letters.[24]
In environments like Git Bash on Windows, the cd command emulates Unix-like behavior within a MinGW 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.[27] Similarly, in Windows Subsystem for Linux (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.[28]
Modern shells like fish extend cd with enhanced interactivity, including rich tab completion for paths and commands, which suggests completions based on history and context as the user types.[29] Fish's cd wrapper also maintains a history 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.[30]
Examples
Basic Navigation
Thecd command facilitates fundamental directory navigation by altering the shell's current working directory, enabling users to move through the file system hierarchy efficiently.[18] In Unix-like systems, specifying an absolute path with cd directs the shell to that location from the root directory, regardless of the starting point; for instance, executing cd /home/user from any directory changes the working directory 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.[18]
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.[18] 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.[1] 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 home directory (symbolized by ~), executing cd ~ implicitly to return to that base location.[18] In contrast, the Windows Command Prompt displays the current directory path without changing it, functioning akin to a query rather than a navigation action.[12]
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.[12] 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, thecd 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:
if cd /tmp; then
ls
fi
if cd /tmp; then
ls
fi
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.[3]
The directory stack provides a mechanism for temporarily saving and restoring working directories, integrating seamlessly with cd. The pushd builtin adds a directory to the stack and changes to it using cd internally, while popd removes the top entry and changes back. Consider this sequence in 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
cd fails during these operations (e.g., due to permissions), pushd and popd return non-zero, preventing inconsistent stack states.[31]
Using variables enhances flexibility, particularly for paths with spaces or dynamic locations. In Bash, expand a variable safely with quotes:
homedir=$[HOME](/page/Home)
cd "$homedir/docs"
homedir=$[HOME](/page/Home)
cd "$homedir/docs"
cd command updates the [PWD](/page/Pwd) environment variable to the new absolute path upon success.[3]
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:
cd nonexistent
cd nonexistent
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.[3][32]
To verify a directory change, combine cd with the pwd builtin, which prints the current working directory:
cd ..
pwd
cd ..
pwd
cd updating PWD correctly.[3]
Implementations and Standards
POSIX Specification
Thecd 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.[33]
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.[33]
POSIX requires cd to fail and return an exit status 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 - operand or when CDPATH search succeeds for a relative path (in which case it prints the absolute pathname used). Standardization 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 environment variable behaviors for better portability, and later revisions up to IEEE Std 1003.1-2024.[33]
Microsoft Implementations
In Microsoft Windows implementations, thecd command and its underlying functionality are provided through the Win32 API, specifically the SetCurrentDirectory function exported from kernel32.dll. This API changes the current directory for the calling process, enabling applications and shells to navigate the file system. The function accepts a path string and returns a boolean indicating success, with the current directory consisting of a drive designator (such as a letter followed by a colon) and a path component.[34][35]
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.[12]
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.[36][37]
Starting with Windows 10, Microsoft has enhanced compatibility with Unix-like behaviors through the Windows Subsystem for Linux (WSL), where cd operates as a standard POSIX-compliant command within Linux 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 group policy or registry settings, allowing SetCurrentDirectory and shell commands to handle extended file paths in modern applications.[28][38]
A key distinction in Windows is the drive-relative nature of current directories: each process 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.[39][35]
Native Windows implementations are proprietary and do not fully comply with POSIX standards for cd, lacking features like symbolic link handling or case-sensitive navigation by default. Partial POSIX compliance is achieved through environments like Cygwin, which emulates a Unix-like shell with a POSIX cd via its DLL layer, or MinGW/MSYS2, which provides a POSIX-compatible bash shell for development tools. These layers translate Windows paths to POSIX semantics but rely on the underlying Win32 API for core operations.