Linux Get Full Path of File
Introduction
When working with the Linux operating system, knowing how to get the full path of a file is a fundamental skill for any user, from beginners to seasoned system administrators. The full path (also called absolute path) specifies the exact location of a file or directory starting from the root (/). Consider this: understanding this concept enables you to reference files reliably in scripts, avoid ambiguity when multiple files share the same name, and troubleshoot permission issues efficiently. This article explains several reliable methods to obtain the full path of a file in Linux, provides step‑by‑step instructions, and answers common questions to ensure you can apply the techniques confidently in your daily workflow Worth keeping that in mind..
Using the realpath Command
The simplest and most direct way to retrieve a file’s full path is by using the realpath utility. This command resolves symbolic links and returns the canonical absolute pathname.
Steps
- Open a terminal – you can launch it from the desktop environment or press
Ctrl+Alt+T. - Type the command:
Replacerealpath<filename>with the name of the file whose path you need. - Press Enter – the terminal will output the complete absolute path.
Why realpath?
- Resolves symlinks: If the file is linked to another location,
realpathfollows the link and shows the true destination. - Works with both files and directories: The same command works regardless of the target type.
- Portable: Available on most modern Linux distributions without additional installation.
Example:
$ realpath document.txt
/home/user/projects/documents/document.txt
In the example above, realpath converts the relative reference document.That's why txt into the full path /home/user/projects/documents/document. txt.
Using readlink Combined with pwd
Another approach involves the readlink command, which can display the target of a symbolic link, combined with the pwd (print working directory) command to build the absolute path Which is the point..
Steps
- Identify the file – ensure you know whether it is a symbolic link or a regular file.
- Run the combined command:
Thereadlink -f-foption tellsreadlinkto resolve all symbolic links, effectively performing the same function asrealpath. - Alternative manual method:
This two‑step process first changes to the parent directory, then prints the current directory’s absolute path, and finally shows the link target.cdpwd readlink
Example:
$ readlink -f link_to_file.txt
/home/user/shared/link_to_file.txt
Here, link_to_file.That's why txt might be a symbolic link pointing to /var/www/html/file. txt; readlink -f collapses the link chain to the full path of the target.
Using stat to Extract Path Information
The stat command provides detailed file metadata, including the full path when invoked with the -c format specifier.
Steps
- Execute the stat command:
This prints the file name (stat -c '%n'%n) along with its path. - Get only the path:
stat -c '%N'%Noutputs the full pathname directly.
Example:
$ stat -c '%N' script.sh
/home/user/scripts/script.sh
stat is especially useful when you need additional file attributes (size, permissions, timestamps) alongside the path Less friction, more output..
Practical Examples in Shell Scripts
In automated scripts, retrieving the full path reliably is crucial. Below are two common patterns And that's really what it comes down to..
Example 1: Getting the Script’s Own Directory
#!/bin/bash
# Get the directory containing this script
SCRIPT_DIR="$(dirname "$(realpath "$0")")"
echo "Script directory: $SCRIPT_DIR"
realpath "$0"resolves the path of the running script ($0).dirnameextracts the directory portion.- The result is a full path that you can safely use to reference other files relative to the script.
Example 2: Processing All Files in a Directory
#!/bin/bash
TARGET_DIR="/var/log"
for file in "$TARGET_DIR"/*.log; do
FULL_PATH=$(realpath "$file")
echo "Processing $FULL_PATH"
# Add your processing commands here
done
Using realpath ensures that even if the glob expands to a symbolic link, the script works with the true location That's the whole idea..
Common Pitfalls and How to Avoid Them
- Relative vs. absolute paths: Using a relative filename (e.g.,
myfile.txt) without first changing directories can lead to unexpected results. Always preferrealpathorreadlink -fto guarantee an absolute path. - Spaces in filenames: Filenames containing spaces break simple command parsing. Enclose variables in quotes:
"$file". - Permissions: If the user lacks read permission on the file or its parent directories,
realpathmay fail. Ensure appropriate permissions or usesudowhen necessary. - Non‑existent files:
realpathwill report an error if the file does not exist. Check existence first with[[ -e "$filename" ]]to avoid misleading output.
FAQ
Q1: Can I get the full path of a directory?
Yes. Both realpath and pwd work on directories. Example: realpath /etc returns /etc Surprisingly effective..
Q2: What if realpath is not installed?
Most distributions ship realpath by default. If missing, you can install the coreutils package or use the readlink -f alternative, which is part of busybox.
Q3: Does the path include the filename?
Yes. The **
full path includes both the directory structure and the filename itself. txt, not just notes.Take this: realpath notes.In real terms, txt returns /home/user/docs/notes. txt And that's really what it comes down to..
Conclusion
Knowing how to obtain a reliable full path is essential for writing portable and dependable shell scripts. Still, if realpath is unavailable, readlink -f is the most common fallback, while pwd can handle simple cases when combined with a relative path. Plus, realpath is generally the best choice because it resolves symbolic links and normalizes the path into an absolute form. Use dirname and basename when you need to split a full path into its directory and filename components.
Not obvious, but once you see it — you'll see it everywhere.
Remember to quote variables to protect against spaces, check that files exist before resolving them, and account for permission restrictions on parent directories. With these tools and precautions, your scripts will handle file paths correctly across different environments and edge cases.