Suppose I have variables dir and file containing strings representing a directory and a filename, respectively . What is the proper way in emacs lisp to join them into a full path to the file?

For example, if dir is "/usr/bin" and file is "ls", then I want "/usr/bin/ls". But if instead dir is "/usr/bin/", I still want the same thing, with no repeated slash.

  • 1
    The wording of the title ("join multiple path components") is really a bit more general than the actual problem, but if anyone is looking for a solution which handles values of "multiple" > 2, see stackoverflow.com/questions/9694661 – phils Nov 21 '12 at 2:02
  • Well, if you can join two components, then you can use recursion to join an arbitrary number. I suppose I consider the two problems equivalent by induction. – Ryan Thompson Nov 24 '12 at 3:55
up vote 54 down vote accepted

Reading through the manual for Directory Names, you'll find the answer:

Given a directory name, you can combine it with a relative file name using concat:

 (concat dirname relfile)

Be sure to verify that the file name is relative before doing that. If you use an absolute file name, the results could be syntactically invalid or refer to the wrong file.

If you want to use a directory file name in making such a combination, you must first convert it to a directory name using file-name-as-directory:

 (concat (file-name-as-directory dirfile) relfile) 

Don't try concatenating a slash by hand, as in

 ;;; Wrong!
 (concat dirfile "/" relfile) 

because this is not portable. Always use file-name-as-directory.

Other commands that are useful are: file-name-directory, file-name-nondirectory, and others in the File Name Components section.

  • 5
    Duh, no wonder I see those concat all over the place, even our manual encourages this use. But it's generally much better to use expand-file-name, except in those cases where you want the end result to be a relative file. – Stefan Nov 20 '12 at 13:47
  • Why is expand-file-name preferred over concat? Other than the style issue, I don't see the practical benefit? – THIS USER NEEDS HELP May 7 '16 at 11:10
  • 1
    Might you also want to call convert-standard-filename on the result if interested in portability? – Sam Brightman Oct 19 '16 at 13:07

You can use expand-file-name for this:

(expand-file-name "ls" "/usr/bin")
"/usr/bin/ls"
(expand-file-name "ls" "/usr/bin/")
"/usr/bin/ls"

Edit: this only works with absolute directory names. I think Trey's answer is the preferable solution.

  • Still useful in many cases. +1 – Ryan Thompson Oct 21 '10 at 5:39

I wanted to join multiple nested directories onto a path. Originally I used multiple expand-file-name calls, like so:

(expand-file-name "b" (expand-file-name "a" "/tmp"))
"/tmp/a/b"

However this is rather verbose, and reads backwards.

Instead I wrote a function which acts like Python's os.path.join:

(defun joindirs (root &rest dirs)
  "Joins a series of directories together, like Python's os.path.join,
  (dotemacs-joindirs \"/tmp\" \"a\" \"b\" \"c\") => /tmp/a/b/c"

  (if (not dirs)
      root
    (apply 'joindirs
           (expand-file-name (car dirs) root)
           (cdr dirs))))

It works like so:

(joindirs "/tmp" "a" "b")
"/tmp/a/b"
(joindirs "~" ".emacs.d" "src")
"/Users/dbr/.emacs.d/src"
(joindirs "~" ".emacs.d" "~tmp")
"/Users/dbr/.emacs.d/~tmp"
  • 1
    Exactly what I needed, thank you! – David Holm Jul 11 '13 at 17:57
  • @dbr, I use a similar function -see my answer be below. Care to comment on what I outlined as the differences and their pros/cons? – sshaw Sep 27 '15 at 19:39

Here's what I use:

(defun catdir (root &rest dirs)
  (apply 'concat (mapcar
          (lambda (name) (file-name-as-directory name))
          (push root dirs))))

Differences from @dbr's:

  1. Returns an "emacs directory name", i.e. a value with a trailing slash
  2. It does not expand the path if root is relative (see notes)
  3. Treats root as the root, whereas joindirs will use the first component starting with "/" as the root.

Notes

Many file handling functions (all, most, ???) will normalize redundant slashes and call expand-file-name (or similar) on relative paths, so #2 and #3 may not really matter.

If you use a convenient file and directory manipulation library f.el, you only need f-join. The below code is for those, who for some reason refuse to use this library.

(defun os-path-join (a &rest ps)
  (let ((path a))
    (while ps
      (let ((p (pop ps)))
        (cond ((string-prefix-p "/" p)
               (setq path p))
              ((or (not path) (string-suffix-p "/" p))
               (setq path (concat path p)))
              (t (setq path (concat path "/" p))))))
    path))

This behaves exactly as Python's os.path.join.

ELISP> (os-path-join "~" "a" "b" "")
"~/a/b/"
ELISP> (os-path-join "~" "a" "/b" "c")
"/b/c"

string-suffix-p doesn't exist before Emacs 24.4, so i wrote my own at Check if a string ends with a suffix in Emacs Lisp.

  • This isn't portable, is it? It uses forward slash as the directory separator and assumes a root that begins with slash. – Ryan Thompson Mar 14 '14 at 16:33

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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