2

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.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
einpoklum
  • 8,772
  • 19
  • 65
  • 129
  • 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 - https://stackoverflow.com/a/229038/2231796 –  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... –  Jun 20 '17 at 22:39

3 Answers3

3

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)"
0

What I do now is

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

I wonder if Bourne Shell had $PWD though.

einpoklum
  • 8,772
  • 19
  • 65
  • 129
  • 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
0

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.

JRFerguson
  • 14,570
  • 3
  • 34
  • 40
  • 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