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. readlink -f is similar (Linux). On macOS, realpath is in coreutils via Homebrew, or use the BSD trick cd "$(dirname foo.txt)" && pwd -P.

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.