An absolute path starts from the root directory (/) and specifies the complete path to a file or directory. A relative path, on the other hand, starts from your current directory. Understanding the distinction is vital for effective file system navigation.
Example 1: Absolute Path to a File
# Display a file's content using its absolute path
cat /etc/hosts
Explanation: This command uses an absolute path to display the contents of the hosts file. The path starts from the root (/), goes through etc, and ends at the file.
Example 2: Relative Path to a File
# Assuming you are in /etc, display the hosts file content
cat hosts
Explanation: This command uses a relative path. It works only if your current directory is /etc, as it looks for the hosts file within the present location.
Example 3: Navigating with an Absolute Path
# Change to the log directory using an absolute path
cd /var/log
Explanation: This command will always take you to the /var/log directory, regardless of your current location in the file system.
Example 4: Navigating with a Relative Path
# From /var, change to the log directory using a relative path
cd log
Explanation: This command is effective if you are currently in the /var directory. It navigates to the log subdirectory relative to your current position.
Example 5: Using .. in a Relative Path
# From /var/log, move to the /var directory
cd ..
Explanation: The .. notation in a relative path refers to the parent directory. This command moves you up one level in the directory hierarchy.
Example 6: Creating a Directory with an Absolute Path
# Create a new directory in your home folder from anywhere
mkdir /home/username/new_directory
Explanation: This command uses an absolute path to create new_directory inside the specified user's home directory. This command will succeed from any location, assuming you have the necessary permissions.
Example 7: Creating a Directory with a Relative Path
# Create a subdirectory within the current directory
mkdir my_stuff
Explanation: This command creates a new directory named my_stuff inside your current working directory. The path is relative to your present location.