cd - Change Directory
Change the current working directory.
Source: src/execution/builtins.f90:builtin_cd
Synopsis
cd [directory]
cd -
cd ~
cd ~username
Description
Changes the shell's current working directory. If no argument is given, changes to the home directory ($HOME).
Options
cd has no flags. The argument is interpreted as a directory path.
Arguments
| Argument | Description |
|---|---|
| (none) | Change to $HOME |
- | Change to previous directory ($OLDPWD) and print it |
~ | Change to home directory |
directory | Change to specified directory |
Behavior
Path Resolution
- If the path contains
/, it's used directly - If the path doesn't contain
/,CDPATHis consulted CDPATHis a colon-separated list of directories to search- Falls back to current directory if not in
CDPATH
Environment Updates
On successful directory change:
OLDPWDis set to the previous directoryPWDis set to the new directory- Terminal title is updated (if interactive and color-capable)
- Directory is added to directory history (for
prevd/nextd)
Implementation Details
From builtins.f90:
! cd with no argument goes to HOME
if (num_args == 0) then
target_dir = get_environment_var("HOME")
! cd - goes to OLDPWD
else if (trim(args(1)) == "-") then
target_dir = shell%oldpwd
print_dir = .true.
Return Value
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Directory not found or permission denied |
Examples
# Go home
cd
# Go to /tmp
cd /tmp
# Go back to previous directory
cd -
# Use CDPATH
export CDPATH="$HOME/projects"
cd myproject # finds ~/projects/myproject
Environment Variables
| Variable | Purpose |
|---|---|
HOME | Default directory when no argument |
CDPATH | Search path for relative directories |
PWD | Updated to new directory |
OLDPWD | Updated to previous directory |
Related Commands
- pushd - Push directory onto stack
- popd - Pop directory from stack
- dirs - Display directory stack
prevd- Go to previous directory in historynextd- Go to next directory in history
Notes
- Symlinks are preserved (logical path behavior)
- The directory history maintained by fortsh is separate from the directory stack (
pushd/popd) cdwithout arguments always goes to$HOME, even if$HOMEis unset (falls back to/)