Suppose I'm running bash on a Unix-ish system - not necessarily Linux and not necessarily very new; and it may not have every bit of software I'd like.

Now, I have a relative path for which I want to get the absolute path. What's the most robust and portable way of doing this?

The answers here seem to mostly assume the GNU core utilities are installed, which I would rather not do.

Bonus points if your answer works on any Bourne Shell variant.

  • One way to be more portable than using pwd and changing dirs(and it's funny that you want a robust way to get absolute paths but didn't said changing dirs were allowed, and also considered this "safer" than install gnu readlink) is to make a little utility in C using realpath() function - stackoverflow.com/a/229038/2231796 – user34720 Jun 20 '17 at 18:54
  • @nwildner: A C compiler is definitely not installed on every system you know... – einpoklum Jun 20 '17 at 21:14
  • Maybe you should add this to your answer, that it requires a portable solution that could also range from embedded to powerfull servers... – user34720 Jun 20 '17 at 22:39

I am not sure if the environment variable $PWD was set in the bourne shell, but the command pwd exists since the old minix and is part of POSIX, so:

abs_path="$(cd "$rel_path" && pwd -P)"
| improve this answer | |
  • +1 for the first suggestion, but the second suggestion is the opposite of what I need, i.e. something I can really not bank on. – einpoklum Jun 20 '17 at 21:15
  • Fair point @einpoklum , readlink removed. – Isaac Jun 20 '17 at 22:51

What I do now is

absolute_path="$(cd "$relative_path"; echo "$PWD")"

I wonder if Bourne Shell had $PWD though.

| improve this answer | |
  • 1
    PWD is in POSIX at least. To avoid the echo, you may use pwd -P: abs_path="$( cd "$rel_path" && pwd -P )" – Kusalananda Jun 20 '17 at 14:33

You can use the Cwd core module from Perl. This module provides functions for determining the pathname of the current working directory.

perl -MCwd -le 'print Cwd::realpath("foo")'

Perl is generally already installed on Linux and Unix. This module has been a part of Perl-5 core since 1994.

| improve this answer | |
  • If I ssh'ed into some minimalistic netbsd distribution embedded on some device - do you think it would have perl 5 and this module? – einpoklum Jun 20 '17 at 21:17

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.