7

Suppose I'm in /path/to/dir. Within this dir is another dir called subdir.

Is there a command I can issue which outputs the full path to subdir, no matter how it is identified? For example:

$ cmd subdir
/path/to/dir/subdir

$ cmd /path/to/dir/subdir
/path/to/dir/subdir
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
George
  • 1,799
  • 2
  • 25
  • 30

2 Answers2

14

coreutils' realpath does the trick:

realpath subdir

and it works however the directory (or file) is specified:

realpath /blah/blah2/subdir
realpath ../blah2/subdir
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
1
function somepath () {
  [ -z "$1" ] && { pwd; return; }
  (cd -P -- "$1" && pwd)
}

Simply creates a subshell (so that the cd doesn't affect your current shell) and prints the cwd. (Edited in a test for the "no parameter" case)

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250