4

I'm looking for a way to normalize arbitrary file paths in bash, resolving . and .. to their absolute values. Examples:

> cd /foo/bar
> normalize_path "."   
/foo/bar
> normalize_path "../baz"
/foo/baz
> normalize_path "../../folder/that/doesnt/exist/"
/folder/that/doesnt/exist

Notice how in the examples above, normalize_path returns a value even if the path does not correspond to a real folder or file. All previous questions about absolute or normalized paths that I've seen on StackOverflow (example 1, example 2) assume the path points to a real file and use realpath or pwd to normalize it, but that will not work for my use case.

In other words, I'm looking for a bash function that purely manipulates paths as strings and does not actually look at the file system, similar to File.getCanonicalPath in Java.

Community
  • 1
  • 1
Yevgeniy Brikman
  • 8,711
  • 6
  • 46
  • 60

1 Answers1

4

Readlink is the way to go, or in your case greadlink. It's in the GNU core utilities package. "brew install coreutils" (if you use home-brew). Then use greadlink -m ../my_silly_filename.txt like rickhg12hs said.

dave234
  • 4,793
  • 1
  • 14
  • 29
  • Ah, I didn't know `greadlink` had a `-m` parameter! I had tried `-f` as was suggested in many other answers, and it does not work if the file doesn't exist. But `-m`, AKA `--canonicalize-missing` does exactly what I want. Thanks! – Yevgeniy Brikman May 25 '15 at 05:16