Every in the terminal is directions to a place. What differs is where the directions start from.
Absolute: from the top of the disk
An absolute path starts with /, the root of the whole disk:
/home/user/projects/site/index.html
Read it as: from the root, into home, into user, into projects, into site, and there is the file. Because it starts at a fixed point, it means the same thing no matter where you are standing.
ls /home/user/downloads
works identically from your home folder, from deep inside a project, from anywhere.
Relative: from where you are
A relative path does not start with /. It starts wherever you currently are:
ls site
cd ../archive
cat index.html
Same directions, different starting point — and the starting point is you.
Quick check
Which of these is an absolute path?
Why this is the error you will meet most
Here is the classic. A tutorial says:
cd src
npm install
You run it and get No such file or directory. The tutorial is not wrong; it just assumed you were standing in the project folder. You were somewhere else, so the relative path src pointed nowhere.
Tip
When a path-based command fails, run pwd before you do anything else. Nine times out of ten the command was fine and your location was not.
Quick check
A command that worked for a colleague fails for you with 'No such file or directory'. What do you check first?
The shorthands
Four pieces show up inside paths constantly:
| Piece | Means |
|---|---|
/ | the root of the disk (at the start) or a separator (in the middle) |
. | the folder you are in right now |
.. | the folder one level up |
~ | your home folder |
~ is worth a second look: it is an absolute path in disguise. ~/projects expands to /home/user/projects, so it works from anywhere, just like a path starting with /. It is shorter to type and it does not hard-code your username, which is why you see it everywhere.
Note
Both forms are correct — this is not a case where one is better practice. Relative paths are shorter and survive moving a project around; absolute paths are unambiguous and survive being run from anywhere. Reach for absolute when you are unsure, relative when you are working inside one project.
Quick check
What does ~/projects expand to for the user `user`?
Try it
You start inside /home/user/projects/site.
pwd— confirm where you are.ls /home/user/downloads— reach a completely different part of the disk with an absolute path, without moving.cd ..— move with a relative path, up intoprojects.pwd— confirm.
Notice that step 2 changed nothing about where you stand. Reading somewhere else and moving somewhere else are different actions.