Unix Paths
Contents
Introduction
When specifying the location of files and folders on a computer system, it is important to know the difference between a relative path and an absolute path, and which is most appropriate for your code.
Absolute Path
An absolute path is the path to a file or directory from the root directory of the computer.
On Unix-like systems, absolute paths begin with / (e.g. /Users/username/).
On Windows systems, absolute paths begin with the drive name (e.g. C:\Users\username\).
In a Unix shell, you print the absolute path of your working directory with the pwd command.
Additional information about Unix shell commands can be found in the Unix Commands guide.
I rarely recommend using absolute paths. The absolute path to a file on one machine will likely be very different from the path to the file on a different machine, which could lead to errors, crashes, and unexpected behaviors in your program.
Relative Path
A relative path allows us to reference the location of a file or directory relative to the working directory.
Certain characters in relative paths can be used to indicate different directories relative to the working directory.
.. is used to indicate the directory one level up from the working directory.
. is used to indicate the working directory.
~ is used to indicate your $HOME directory.
If you do not know the location of your home directory, you can print it using the echo command in a Unix shell command line interface (CLI).
echo $HOME
Additional information about Unix shell commands can be found in the Unix Commands guide.
cd with Relative Paths
In a Unix shell, you can use the cd command to change your working directory. Let’s say we have three directories: Level-0/Level-1/Level-2.
From Level-0, cd Level-1 will take you to Level-1.
From Level-1, cd .. will take you to Level-0.
From Level-1, cd ./Level-2 will take you to Level-2.
From Level-2, cd ../.. will take you to Level-0.
From Level-0, cd Level-1/Level-2 will take you to Level-2.
From Level-1, cd .././Level-1/Level-2/.. will take you to Level-1.
Additional information about Unix shell commands can be found in the Unix Commands guide.
Paths with Spaces
When executing commands in a Unix shell, if any folder in a directory path has a space character in its name, the path must be surrounded by quotes.
cd '../directory with spaces/sub-1'
ls './directory with spaces'
mkdir 'directory with spaces'
Additional information about Unix shell commands can be found in the Unix Commands guide.
Resources and References
For additional information about file paths, the following resources may be helpful:
GeeksforGeeks - Path Name in File Directory
Tutorials Point - Path Name in File Directory
Codecademy Docs - File System Structure
freeCodeCamp - File Directories Explained by Getting Dressed in the Morning