Website Vidya
Linux & ServersStep-by-Step Guide

pwd Command in Linux: Print Working Directory Guide

Learn pwd command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
pwd Command in Linux: Print Working Directory Guide
AI Executive SummaryWebsiteVidya AI

9 min read

Learn pwd command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What pwd Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Spatial orientation and accurate path resolution across the filesystem rely on the pwd command in linux. Short for 'print working directory', pwd is one of the very first commands encountered by every Unix user, reporting the full absolute path from the filesystem root (/) to the calling process's current working directory.

While conceptually simple, pwd embodies important architectural behaviors in modern Linux environments. Like cd, pwd exists both as a fast shell built-in utility (in bash, zsh, dash) and as a standalone external binary executable (/bin/pwd provided by GNU coreutils).

The most significant operational distinction in pwd lies in how it handles symbolic links. By understanding the difference between logical mode (pwd -L) and physical mode (pwd -P), system administrators and automation engineers can avoid path confusion when working within complex symlink structures, container volumes, and automated build pipelines.

Advertisement
pwd Command in Linux: Print Working Directory Guide — syntax, flags, and practical terminal workflow diagram
pwd Command in Linux: Print Working Directory Guide — command syntax, key options, and production workflow reference.

What pwd Does and When to Use It

Under the hood, the Linux kernel tracks the current working directory of every active process within its task_struct structure, specifically through a pointer named fs_struct->pwd. This pointer references the dentry (directory entry) and vfsmount of the active directory in kernel memory.

When the standalone /bin/pwd binary or pwd -P executes, it invokes the getcwd(2) system call. The kernel traverses the dentry tree upward toward the root dentry, reading parent directory pointers and assembling the canonical physical pathname. In contrast, the shell built-in pwd (or pwd -L) reads the shell's internal $PWD environment variable, which reflects the logical sequence of directory names typed by the user, preserving any symbolic link names.

At the operating system level, pwd (distributed in coreutils / bash) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how pwd resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.

Availability and Installation Across Linux Distributions

The pwd utility is packaged in coreutils / bash across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether pwd is installed and inspect which binary path and version your shell resolves:

type -a pwd
pwd --version 2>/dev/null || man -f pwd

# Illustrative output (reviewed against documentation)
pwd is /usr/bin/pwd
pwd (coreutils / bash)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

pwd [-L | -P]

The command synopsis is exceptionally compact: pwd [-L | -P]. Because pwd prints only the current working directory, it takes no file operands or target path arguments.

The two mutual exclusive flags are -L (--logical) and -P (--physical). If no flag is specified, the shell built-in defaults to -L, displaying the path including any symbolic link segments. The -P flag dereferences all symbolic links, reporting the real underlying physical directory structure on the disk.

  • 0 — Working directory path successfully resolved and printed to standard output.
  • 1 — Operational failure, such as unreadable parent directory or invalid command-line option.
  • 2 — Severe syntax error or memory allocation failure.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-L--logicalPrints the logical working directory from $PWD, preserving symlink names (default).
-P--physicalResolves all symbolic links and prints the real physical directory path on disk.
--help--helpDisplays command help information and exits (GNU /bin/pwd only).
--version--versionOutputs version information and exits (GNU /bin/pwd only).
$PWDEnvironment VariableContains the logical current working directory string maintained by the shell.
$OLDPWDEnvironment VariableContains the previous working directory string before the last cd command.

The distinction between pwd -L and pwd -P becomes paramount when debugging application servers and container mounts. If an application is installed in /opt/releases/v2.4.1/app and symlinked to /var/www/active_app, navigating to the folder and running pwd prints /var/www/active_app.

Advertisement

However, running pwd -P prints /opt/releases/v2.4.1/app. In shell scripts that generate log filenames, export environment variables, or construct relative paths, relying on pwd -P guarantees that scripts interact with the true physical path rather than an ephemeral symlink alias.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Print the Current Working Directory

Display the full absolute path of the directory you are currently in.

cd /var/log
pwd

# Illustrative output (reviewed against documentation)
/var/log

The shell outputs the absolute path from the root directory to the active directory.

2. Compare Logical vs Physical Path Resolution Across Symlinks

Observe how -L preserves symlink names while -P resolves physical disk locations.

mkdir -p /opt/app_build /tmp/shortcuts
ln -s /opt/app_build /tmp/shortcuts/active
cd /tmp/shortcuts/active
pwd -L
pwd -P

# Illustrative output (reviewed against documentation)
/tmp/shortcuts/active
/opt/app_build

pwd -L reflects the logical symlink path, whereas pwd -P resolves the real physical location in /opt.

3. Verify the Standalone Binary vs Shell Built-in

Inspect how the shell resolves pwd and execute the coreutils standalone binary directly.

type -a pwd
/bin/pwd

# Illustrative output (reviewed against documentation)
pwd is a shell builtin
pwd is /bin/pwd
/opt/app_build

type -a confirms pwd is a shell built-in; executing /bin/pwd directly bypasses the shell and runs the physical binary.

4. Store Current Working Directory in a Script Variable

Capture the current directory inside a bash variable for reliable return navigation.

CURRENT_DIR=$(pwd)
echo "Script started in: $CURRENT_DIR"

# Illustrative output (reviewed against documentation)
Script started in: /opt/app_build

Command substitution $(pwd) captures the output string cleanly into the variable.

5. Read the $PWD Shell Environment Variable Directly

Access the working directory string instantaneously without executing a subshell.

echo "Environment PWD: $PWD"

# Illustrative output (reviewed against documentation)
Environment PWD: /tmp/shortcuts/active

The $PWD environment variable is updated automatically by bash upon every successful cd.

6. Resolve the Directory Containing the Running Script

The canonical sysadmin one-liner to determine the exact physical directory of a bash script.

SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd -P)
echo "Script lives in: $SCRIPT_DIR"

# Illustrative output (reviewed against documentation)
Script lives in: /home/admin/scripts

Combining dirname with cd and pwd -P reliably determines the script's real folder regardless of where it is invoked from.

Real-World Workflows, Pipelines, and Shell Automation

Self-Locating Automation Script Bootstrap Workflow

In production bash scripts, determine the absolute physical directory containing the script so relative configuration and asset paths can be loaded reliably without depending on the caller's CWD.

#!/usr/bin/env bash
set -euo pipefail

# Determine the physical directory containing this script
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
CONFIG_FILE="${SCRIPT_DIR}/../config/app.env"

echo "Script physical directory: ${SCRIPT_DIR}"
if [ -f "${CONFIG_FILE}" ]; then
  echo "Found configuration file at: ${CONFIG_FILE}"
else
  echo "Notice: Configuration file not present at expected relative path."
fi

# Illustrative output (reviewed against documentation)
Script physical directory: /opt/myapp/bin
Found configuration file at: /opt/myapp/bin/../config/app.env

Using BASH_SOURCE with dirname and pwd -P guarantees that the script resolves its companion directories accurately.

Automated Directory Change Rollback Guard in Scripts

When performing operations in multiple directory locations, record the origin directory and enforce safe restoration before script termination.

ORIGIN_DIR="$(pwd -P)"
echo "Starting workflow in: $ORIGIN_DIR"

cleanup() {
  echo "Restoring original directory: $ORIGIN_DIR"
  cd "$ORIGIN_DIR"
}
trap cleanup EXIT

# Temporarily navigate to build directory
cd /tmp
echo "Operating in temporary workspace: $(pwd)"

# Illustrative output (reviewed against documentation)
Starting workflow in: /var/www/html
Operating in temporary workspace: /tmp
Restoring original directory: /var/www/html

The trap EXIT handler ensures that the script returns cleanly to the starting directory even if an unexpected error occurs.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding pwd inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

In Linux, resolving a physical path with getcwd(2) requires execute (x) search permissions on every directory component ascending to the filesystem root. If an unprivileged user enters a directory where a parent directory lacks read/execute permissions, getcwd(2) may fail with 'Permission denied'.

Do not rely solely on the $PWD environment variable in security-sensitive programs. An attacker can manipulate $PWD before launching a setuid or sudo binary. Always use the getcwd(3) C library call or /bin/pwd -P to determine the true canonical working directory.

GNU/Linux, BSD, and BusyBox Implementation Differences

The pwd utility and its -L and -P flags are standardized under POSIX.1-2017 and are universal across Linux, macOS, FreeBSD, and BusyBox.

The shell built-in pwd is present in bash, dash, ksh, and zsh. In minimal POSIX shells without built-in pwd, the external /bin/pwd binary is executed transparently.

Troubleshooting Common Errors and Diagnostics

pwd: error retrieving current directory: getcwd: cannot access parent directories

Root Cause: The current working directory (or one of its parent folders) was deleted or unmounted while your shell was still inside it.

Resolution: Navigate back to a valid existing directory (such as cd / or cd ~) to restore shell context.

cd ~
pwd

pwd shows logical symlink instead of physical folder path

Root Cause: The shell built-in defaults to -L (logical), reflecting the symlink path stored in $PWD.

Resolution: Pass the -P flag to force physical path resolution: pwd -P.

pwd -P

Script fails because relative paths resolve to wrong directory

Root Cause: The script was executed from a different directory than assumed, making relative paths invalid.

Resolution: Always resolve the script's directory dynamically using SCRIPT_DIR="$(cd -- "$(dirname -- "$0")" && pwd -P)".

SCRIPT_DIR="$(cd -- "$(dirname -- "$0")" && pwd -P)"

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
pwd is a command that can query the operating system for the current working directory, supporting flags like -P to resolve physical paths. echo $PWD simply prints the value of the shell's internal PWD variable, which only stores the logical path.
If you entered a directory through a symbolic link, pwd -L shows the path including the symlink name. pwd -P dereferences all symlinks and shows the real physical storage directory on the disk.
Yes. If the directory you are currently in is deleted by another process, or if permissions on an ancestor directory are revoked so that the kernel cannot trace the path back to the root (/), pwd will fail with a getcwd error.
pwd is both. It is built directly into shells like bash and zsh for speed, and it is also installed as a standalone executable binary (/bin/pwd) in GNU coreutils for compatibility.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout