0

Is there some native function(shell, linux command) to merge/compute the full path?

example:

old_path="~/test1/test2/../dir3//file.txt"
new_path=FUN($old_path)

echo "$new_path"   // I want get this "/home/user/test1/dir3/file.txt"    
Jens
  • 69,818
  • 15
  • 125
  • 179
Yifan Wang
  • 504
  • 6
  • 13

2 Answers2

0

Does

  new_path=$(eval cd "$old_path"; pwd)

work for you? You can also use pwd -P if you want symlinks resolved. You can make life easier if you use $HOME instead of ~ in old_path. Then you don't need the eval.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Or use `pwd -P`. Then `eval` is unnecessary. – glglgl Jun 13 '13 at 06:31
  • @glglgl The eval is always needed to perform tilde expansion. – Jens Jun 13 '13 at 06:54
  • Luckily, my `bash` hasn't read this comment so it doesn't know about. If I enter `echo $(cd ~/mp3; pwd -P)`, I get `/home/glglgl/mp3`. If I'd put it into a variable instead, the same would happen. – glglgl Jun 13 '13 at 07:00
  • does it change current working path? – Yifan Wang Jun 13 '13 at 07:49
  • @glglgl No it doesn't. You're running a different command and I suggest you actually *do* put it in a variable with quotes. If `foo="~"; cd $foo` works in your bash, it is broken. The problem is that tilde expansion occurs *before* parameter expansion when using `$foo`. – Jens Jun 13 '13 at 08:50
  • @YifanWang No it doesn't change the current working dir because the `cd` is run in a subshell. – Jens Jun 13 '13 at 08:57
0

Use readlink:

$ readlink -m ~/foo.txt
/home/user/foo.txt
$ readlink -m ~/somedir/..foo.txt
/home/user/foo.txt

It also handles symlinks.

devnull
  • 118,548
  • 33
  • 236
  • 227
  • This doesn't work if the pathname is in a variable. – Jens Jun 13 '13 at 06:56
  • @Jens: You're probably referring to tilde expansion in a variable. In that event, it'd make sense to use `${HOME}` instead as you've mentioned. – devnull Jun 13 '13 at 08:11