I know that if you have a file one.txt in ~/Documents and you cd ~/Documents then realpath one.txt will print:


However what if you want to print the path of a file in a different directory. For example, cd a/b and there is a file two.txt in directories a2/b2 then how does a person print the absolute path of two.txt by just passing two.txt to a command.

Looking to do something like realpath two.txt that works from a different directory.


Just give realpath the relative path from the current directory:

$ pwd
$ realpath ../../../.profile

The GNU realpath utility would not be able to find my .profile file, or produce the absolute path for it, without me giving it a hint about where it was located. In your case, you could potentially have any number of files called two.txt, so realpath must at least be given a relative path from the current directory to be able to give an absolute pathname for the file.

In a Unix filesystem, a file is uniquely identified by a pathname (either relative or absolute). A filename can not uniquely identify any file other than one of the files in the current directory.

To locate all regular files called two.txt in or under your home directory, and get their pathnames relative to $HOME:

find "$HOME" -type f -name two.txt
  • That could work but what if you cannot give realpath the relative path because the file is in a different branch. For example instead of .profile you wanted to query a file in /etc? Perhaps realpath does not have this functionality because the developers wanted to avoid printing the paths of files with the same name but in practice how many files can be identical in name? – starboy Jul 25 '18 at 19:07
  • @MyWrathAcademia Files are identified uniquely by pathnames. Either a relative pathname from the current directory, or an absolute pathname from the root directory. A filename can not uniquely identify a file other than in the current directory. – Kusalananda Jul 25 '18 at 19:16
  • Yes, may be I should rephrase my question. Can a relative path name from the current directory be used with realpath for a file that is on a different branch of the directory tree? – starboy Jul 25 '18 at 19:29
  • @MyWrathAcademia The answer is yes. See my answer above for an example. – Kusalananda Jul 25 '18 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.