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
  • 67,283
  • 35
  • 116
  • 255
George
  • 1,809

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
  • 434,908
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
  • 67,283
  • 35
  • 116
  • 255