9
    (parent-dir "/home/sk/parent/ab.el")

gives

    "/home/sk/parent"

then,

(parent-dir "/home/sk/parent")

gives

"/home/sk"

Any elisp function as parent-dir that gives basepath for both file path & dir path?

13

file-name-directory does what you request.

However, (file-name-directory "/home/sk/parent/") (with a trailing slash) returns that same directory, not its parent.

This does what I'm guessing you really want:

(file-name-directory (directory-file-name "/home/sk/parent/ab.el")) ; => "/home/sk/parent/"
(file-name-directory (directory-file-name "/home/sk/parent/")) ; => "/home/sk/"
(file-name-directory (directory-file-name "/home/sk/parent")) ; => "/home/sk/"

And library Dired+ uses this function:

(defun diredp-parent-dir (file &optional relativep)
  "Return the parent directory of FILE, or nil if none.
Optional arg RELATIVEP non-nil means return a relative name, that is,
just the parent component."
  (let ((parent  (file-name-directory (directory-file-name (expand-file-name file))))
        relparent)
    (when relativep
      (setq relparent  (file-name-nondirectory (directory-file-name parent))))
    (and (not (equal parent file))  (or relparent  parent))))
0
(defun parent-directory (dir)
  (unless (equal "/" dir)
    (file-name-directory (directory-file-name dir))))

Taken from https://stackoverflow.com/a/14096693/5103881

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.