How do I get a parent directory for a file?
I want it to be safe on all kind of names:
.
..
path/to/my/file
/absolute/path/to/my/file
'-rf --no-preserve-root whatever'/test.zip
(symbolic links)
`'"`'{(})
I am more interested getting the canonical location on the file system than in traversing the path stated in the filename.
Note that there are similar questions to this one, but none of them focuses on correctness, relative/absolute paths and "unsafe" names:
[1] bash get the parent directory of current directory
Really safe solution:
If your system does not have
realpath
but does havereadlink
, this should work:Bash's
cd
command has a couple of interesting but little-used options,-P
and-L
.So ... if you're looking for the physical location in the filesystem of your current working directory, you could use something like this:
In your comments, you mentioned that you're looking for the parent directory of the directory containing a file -- so, if a path is
/foo/bar/baz/filename
, you'd be looking for/foo/bar
.To get this, I would suggest a combination of
cd -P
and parameter expansion. Since you know that the/
character can never exist as part of a filename, the following might work for you:This works by using
cd -P
to "get" the physical location of the file, then parameter expansion to strip off the last item in the path.