Skip to content
C.W.K.
Stream
Lesson 04 of 12 · published

Absolute vs Relative Paths

~10 min · paths, absolute, relative

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Two ways to point at a file

An absolute path starts at the root: /Users/me/projects/foo.txt. It always means the same file no matter where you are. A relative path is interpreted from your current working directory: projects/foo.txt means "projects/foo.txt under wherever I am right now."

Special navigation tokens

  • . — current directory
  • .. — parent directory
  • ~ — your home directory
  • ~user — that user's home
  • - (only with cd) — previous directory

Combine them: cd ../../sibling-project, cp ./local.txt ~/backups/.

When to use which

Scripts that run from cron or CI should use absolute paths — you don't know what their working directory will be. Day-to-day shell work uses relative paths because it's faster and reads naturally. The shebang line at the top of every script is always absolute: #!/usr/bin/env bash is interpreted by the kernel, which has no concept of "current directory."

Resolving paths programmatically

realpath foo.txt turns a relative path into an absolute one and resolves symlinks. Current macOS releases include realpath; on older releases that lack it, install GNU coreutils through Homebrew. A BSD-only fallback is cd "$(dirname foo.txt)" && pwd -P. GNU and BSD behavior can differ for options and nonexistent paths, so inspect the implementation you are running.

Relative paths preserve relationships

Relative paths can keep project links and configuration movable, while absolute paths clarify anchors for services and backups. Choose from what moves and what remains the reference point, not from which string is shorter.

Normalization is not authorization

Collapsing .. and producing an absolute path does not remove symlink or mount boundaries. For untrusted input, resolve against the filesystem and prove the result remains inside the allowed root.

A path expresses a trust boundary as well as a location.

Code

Walk between paths·bash
cd ~
ls projects/                # relative
ls /Users/$(whoami)/projects/    # absolute equivalent
cd ../../tmp                # relative w/ ..
realpath ../../tmp || readlink -f ../../tmp

External links

Exercise

From your home directory, run both ls projects/ and ls /Users/$(whoami)/projects/ and confirm identical output. Then cd /tmp and try the same — the relative one fails because /tmp doesn't have your projects, but the absolute one still works.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.