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
-L, --logical
: Print logical working directory (with symbolic links)-P, --physical
: Print physical working directory (resolve symbolic links)
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
-
Script Location Reference
# Get script's directory SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-
Build Systems
# Save original directory original_dir=$(pwd) cd build/ make cd "$original_dir"
-
Path Verification
# Check if in correct directory if [ "$(pwd)" != "/expected/path" ]; then echo "Wrong directory!" exit 1 fi
Tips and Tricks
-
Store Current Directory
OLD_PWD=$(pwd) cd /some/other/path # Later... cd "$OLD_PWD"
-
Use in Command Substitution
# Create backup with current path name tar -czf "backup-$(basename $(pwd)).tar.gz" .
-
Combine with Other Commands
# List files with full paths find "$(pwd)" -type f -name "*.txt"
Best Practices
-
Quote Directory Names
dir="$(pwd)" # Handles spaces in paths
-
Check Command Success
if ! dir="$(pwd)"; then echo "Failed to get current directory" exit 1 fi
-
Use with cd
# Save and restore location pushd "$(pwd)" > /dev/null # Do work... popd > /dev/null
Common Errors and Solutions
-
Permission Denied
- Solution: Check directory permissions
- Ensure you have execute (x) permission
-
No Such File or Directory
- Current directory might have been deleted
- Solution: cd to a valid directory
-
Symbolic Link Issues
- Use
-P
to resolve actual path - Use
-L
to maintain symbolic links
- Use
Related Commands
cd
: Change directorydirname
: Strip last component from pathbasename
: Strip directory from pathrealpath
: Resolve path (including symlinks)
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.