Skip to content

Linux pwd Command: Print Working Directory Guide

Published: at 03:31 PMSuggest Changes

The pwd (print working directory) command displays your current location in the Linux filesystem. While simple, it’s crucial for navigation and scripting.

Basic Syntax

pwd [options]

Common Options

Real-World Examples

1. Basic Usage

$ pwd
/home/user/documents

2. Physical vs Logical Path

# With symbolic link
$ ln -s /var/www/html web
$ cd web
$ pwd -L
/home/user/web
$ pwd -P
/var/www/html

3. In Scripts

#!/bin/bash
current_dir=$(pwd)
echo "Working from: $current_dir"

Common Use Cases

  1. Script Location Reference

    # Get script's directory
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    
  2. Build Systems

    # Save original directory
    original_dir=$(pwd)
    cd build/
    make
    cd "$original_dir"
    
  3. Path Verification

    # Check if in correct directory
    if [ "$(pwd)" != "/expected/path" ]; then
        echo "Wrong directory!"
        exit 1
    fi
    

Tips and Tricks

  1. Store Current Directory

    OLD_PWD=$(pwd)
    cd /some/other/path
    # Later...
    cd "$OLD_PWD"
    
  2. Use in Command Substitution

    # Create backup with current path name
    tar -czf "backup-$(basename $(pwd)).tar.gz" .
    
  3. Combine with Other Commands

    # List files with full paths
    find "$(pwd)" -type f -name "*.txt"
    

Best Practices

  1. Quote Directory Names

    dir="$(pwd)"  # Handles spaces in paths
    
  2. Check Command Success

    if ! dir="$(pwd)"; then
        echo "Failed to get current directory"
        exit 1
    fi
    
  3. Use with cd

    # Save and restore location
    pushd "$(pwd)" > /dev/null
    # Do work...
    popd > /dev/null
    

Common Errors and Solutions

  1. Permission Denied

    • Solution: Check directory permissions
    • Ensure you have execute (x) permission
  2. No Such File or Directory

    • Current directory might have been deleted
    • Solution: cd to a valid directory
  3. Symbolic Link Issues

    • Use -P to resolve actual path
    • Use -L to maintain symbolic links

Advanced Usage

1. In Functions

get_project_root() {
    local dir="$(pwd)"
    while [ "$dir" != "/" ]; do
        [ -f "$dir/package.json" ] && echo "$dir" && return
        dir="$(dirname "$dir")"
    done
}

2. Path Manipulation

# Get parent directory
parent="$(dirname "$(pwd)")"

# Get current directory name
current="$(basename "$(pwd)")"

3. With Find Command

# Find files relative to current directory
find "$(pwd)" -maxdepth 1 -type f

The pwd command is essential for shell scripting and daily system navigation. While simple, it provides crucial functionality for path manipulation and directory tracking in scripts and interactive use.


Previous Post
Linux mkdir Command: Creating Directories Made Simple
Next Post
Linux cd Command: Complete Guide to Directory Navigation