How to define pwd as a variable in Unix shell

Learn how to define pwd as a variable in unix shell with practical examples, diagrams, and best practices. Covers shell, unix, pwd development techniques with visual explanations.

Mastering Your Current Directory: Defining PWD as a Variable in Unix Shell

Hero image for How to define pwd as a variable in Unix shell

Learn how to effectively capture and utilize the current working directory (PWD) as a variable in various Unix shell environments, enhancing script flexibility and command-line efficiency.

The pwd command (Print Working Directory) is a fundamental utility in Unix-like operating systems, displaying the full path of your current location in the file system. While simply typing pwd is useful for immediate feedback, integrating this information into shell variables unlocks powerful scripting capabilities and streamlines command-line operations. This article will guide you through various methods to define and use pwd as a variable, covering common shell environments and best practices.

Understanding PWD and its Importance

The PWD environment variable is automatically maintained by the shell and always reflects your current working directory. However, when you need to capture this value at a specific point in time or manipulate it within a script, assigning it to a custom variable becomes essential. This allows you to reference the path without re-executing pwd, making your scripts more robust and efficient, especially when dealing with relative paths or changing directories during execution.

flowchart TD
    A[Start Shell Session] --> B{Change Directory?}
    B -- Yes --> C[Update PWD Environment Variable]
    B -- No --> D[PWD Remains Current]
    C --> E[Execute `pwd` command]
    D --> E
    E --> F["Output: /home/user/project"]
    F --> G["Assign to custom variable: `MY_DIR=$(pwd)`"]
    G --> H[Use MY_DIR in commands/scripts]
    H --> I[End]

Flowchart illustrating the lifecycle and usage of the PWD variable.

Methods for Assigning PWD to a Variable

There are several ways to assign the output of the pwd command to a shell variable. The most common and recommended methods involve command substitution, which allows the output of a command to be used as part of another command or assigned to a variable.

# Method 1: Using command substitution with $()
CURRENT_DIR=$(pwd)

# Method 2: Using backticks (less recommended)
# CURRENT_DIR=`pwd`

# Method 3: Directly using the PWD environment variable
# This captures the *current* PWD, but won't update if you cd later
INITIAL_DIR="$PWD"

# Example usage
echo "The current directory is: $CURRENT_DIR"
ls "$CURRENT_DIR"

Assigning pwd output to a variable in Bash.

Let's break down each method:

1. Command Substitution ($()):

This is the most robust and recommended method. The shell executes the command inside the parentheses (pwd) and substitutes its standard output into the variable assignment. This ensures you get the absolute, canonical path.

2. Backticks (`):

An older form of command substitution. While it works, it's generally discouraged due to issues with nesting and escaping special characters. It's best to avoid it in new scripts.

3. Directly Using $PWD:

The shell automatically maintains the $PWD environment variable. You can directly assign its value to another variable. The key difference here is that $PWD always reflects the shell's current working directory. If you cd after assigning INITIAL_DIR="$PWD", then INITIAL_DIR will retain the path from when it was assigned, while $PWD will update to the new directory.

Practical Examples and Use Cases

Defining pwd as a variable is incredibly useful in scripts for tasks like creating temporary files, logging, or referencing project roots.

#!/bin/bash

# Capture the script's starting directory
SCRIPT_START_DIR="$(pwd)"

echo "Script started in: $SCRIPT_START_DIR"

# Change directory for some operations
mkdir -p temp_data
cd temp_data

echo "Now in: $(pwd)"

# Create a file in the original directory using the variable
echo "This is a log entry." > "$SCRIPT_START_DIR/script_log.txt"

# Return to the original directory (optional)
cd "$SCRIPT_START_DIR"

echo "Returned to: $(pwd)"

cat script_log.txt

A shell script demonstrating capturing and using the initial working directory.

While pwd usually provides the canonical path, sometimes symbolic links can complicate matters. If your current directory is a symbolic link, pwd might show the logical path (the path you used to get there), not the physical path (the actual location on disk). For scenarios requiring the absolute, resolved physical path, readlink -f (or realpath on some systems) is invaluable.

# Create a test directory and a symbolic link to it
mkdir /tmp/real_dir
ln -s /tmp/real_dir /tmp/link_dir

# Change into the symbolic link
cd /tmp/link_dir

# Using pwd
LOGICAL_PATH=$(pwd)
echo "Logical path (pwd): $LOGICAL_PATH"

# Using readlink -f
PHYSICAL_PATH=$(readlink -f .)
echo "Physical path (readlink -f .): $PHYSICAL_PATH"

# Clean up
cd -
rm -rf /tmp/real_dir /tmp/link_dir

Distinguishing between logical and physical paths using pwd and readlink -f.

In this example, pwd reports /tmp/link_dir, which is the path you navigated through. However, readlink -f . (where . refers to the current directory) resolves the symbolic link and provides the actual physical path: /tmp/real_dir. Choose the method that best suits whether you need the logical or physical path.