How to Get the Full Path of a File in Linux/Unix

Obtaining the full path of a file in Linux or Unix systems is essential for navigating the file system and executing commands or scripts. Here’s how you can retrieve the absolute path of a file:

Using realpath Command

  1. Using realpath: The realpath command resolves all symbolic links, references, and relative path components to provide the absolute path of a file.
realpath /path/to/file

Replace /path/to/file with the actual path of the file you want to retrieve the absolute path for.

Example:

realpath ~/Documents/myfile.txt

This command returns the absolute path of ~/Documents/myfile.txt, resolving any symbolic links or references along the way.

Using readlink Command

  1. Using readlink: The readlink command is primarily used to print the value of symbolic links. When used with the -f option, it resolves the absolute path of a file.
readlink -f /path/to/file

Example:

readlink -f ~/Documents/myfile.txt

This command also resolves symbolic links and prints the absolute path of ~/Documents/myfile.txt.

Using pwd Command (Current Working Directory)

  1. Using pwd: If you are currently in the directory containing the file, you can use pwd (print working directory) along with the relative path of the file to obtain its absolute path.
   cd /path/to/directory
   pwd

Example:

   cd ~/Documents
   pwd

After navigating to ~/Documents, the pwd command outputs /home/user/Documents, indicating the absolute path of the current directory.

Conclusion

Obtaining the full path of a file allows you to reference it accurately in commands, scripts, or configurations on Linux and Unix systems. Whether using realpath, readlink, or pwd, these commands provide different methods to retrieve and utilize file paths effectively in your daily operations and scripting tasks.