Linux Paths and Navigation Cheat Sheet

Navigate Linux paths efficiently with cd, pushd/popd, globbing, basename, dirname, and canonical path tools.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Path Basics
Show current path via shell variable
echo "$PWD"

# Print current directory using shell state.

Get basename
basename /var/log/nginx/access.log

# Extract the last path component.

Get dirname
dirname /var/log/nginx/access.log

# Extract the parent directory path.

Resolve relative path from base
realpath --relative-to=/var/log /var/log/nginx/access.log

# Produce canonical path using a base directory.

## Globbing
Match text files
ls *.txt

# Expand shell glob to files ending in .txt.

Recursive glob in Bash
shopt -s globstar && ls **/*.log

# Match files recursively with globstar enabled.

Include dotfiles in globbing
shopt -s dotglob && printf '%s
' *

# Enable matching hidden files with shell globs.

Brace expansion
mkdir -p project/{src,tests,docs}

# Generate multiple path names quickly.

## Directory Stack
Push and change directory
pushd /etc/nginx

# Change directory and push previous one onto stack.

Return to previous stacked directory
popd

# Pop top directory from stack and change to it.

Clear directory stack
dirs -c

# Remove entries from shell directory stack.

## Path Recipes
Iterate over files safely
find . -type f -print0 | while IFS= read -r -d '' f; do printf '%s
' "$f"; done

# Use NUL delimiters for filenames with spaces/newlines.

Convert relative path to absolute path
realpath ./scripts/deploy.sh

# Resolve a relative path from current directory.

Test whether path exists
[[ -e /etc/hosts ]] && echo exists

# Check file or directory existence in shell scripts.

More in Linux Paths and Navigation

No other published sheets yet.

Recommended next

No recommendations yet.