3

I have some custom elisp functions that need to run shell scripts using shell-command. I would like to use a relative path to the script, e.g.:

(shell-command "./run.sh")

rather than an absolute one:

(shell-command "~/blah/blah/blah/run.sh")

But the relative path will only work if the working directory contains the script. I don't want to use an absolute path, because the path to the shell script might change. However, the shell script will always be in the same directory as the .el file where the function is defined, so I thought I could leverage that fact, and use a relative path instead, I just can't figure out how to do it. I know that I can change the default-directory, but I don't know how to do that without using an absolute path.

Is there a way for me to tell the function to use the directory that contains its .el file as the default-directory, or is there maybe a better solution?

4

You can define a variable in the script that records the directory:

(defvar my-shell-directory
  (if load-file-name
      (file-name-directory load-file-name)
    default-directory))

You can then use it in your own functions:

(defun my-shell-command (cmd)
  (shell-command (expand-file-name cmd my-shell-directory)))

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.