0
0
Linux CLIscripting~5 mins

Absolute vs relative paths in Linux CLI - CLI Comparison

Choose your learning style9 modes available
Introduction
When you work with files and folders on your computer, you need to tell the system where to find them. Absolute and relative paths are two ways to do this. Absolute paths give the full address from the root, while relative paths give the address from where you currently are.
When you want to open a file from anywhere on your system without confusion.
When you are inside a folder and want to access a file nearby without typing the full address.
When writing scripts that need to work regardless of where they are run from.
When moving between folders in the terminal and running commands on files.
When linking files or folders in configuration files or shortcuts.
Commands
Shows your current folder's full path, so you know where you are in the system.
Terminal
pwd
Expected OutputExpected
/home/user/projects
Lists files in the /etc folder using an absolute path, starting from the root.
Terminal
ls /etc
Expected OutputExpected
passwd hosts hostname
Lists files in the documents folder one level up from your current folder using a relative path.
Terminal
ls ../documents
Expected OutputExpected
resume.pdf notes.txt
Displays the content of the hostname file using an absolute path to avoid confusion.
Terminal
cat /etc/hostname
Expected OutputExpected
my-computer
Shows the content of notes.txt using a relative path from your current folder.
Terminal
cat ../documents/notes.txt
Expected OutputExpected
Meeting at 10am Buy groceries
Key Concept

If you remember nothing else from this pattern, remember: absolute paths start from the root and always point to the same place, while relative paths start from your current folder and change depending on where you are.

Common Mistakes
Using a relative path without knowing your current folder.
The command fails or accesses the wrong file because the starting point is different than expected.
Use pwd to check your current folder before using relative paths, or use absolute paths for certainty.
Typing an absolute path but missing the leading slash (/).
The system treats it as a relative path and looks in the wrong place.
Always start absolute paths with a slash to indicate the root folder.
Summary
Use pwd to find your current folder's absolute path.
Absolute paths start with / and always point to the same location.
Relative paths depend on your current folder and use ./ or ../ to move around.