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.