14

I call git get the toplevel dir (according to Is there a way to get the git root directory in one command? ).

(let ((tmpbuffer (get-buffer-create (make-temp-name "git"))))
  (call-process "git" nil tmpbuffer nil "rev-parse" "--show-toplevel")
  (with-current-buffer tmpbuffer
    (with-output-to-string
      (princ (buffer-string))
      (kill-buffer))))

But there's a trailing newline in the string returned. I'm not sure how to get rid of it.

Community
  • 1
  • 1
Reactormonk
  • 21,472
  • 14
  • 74
  • 123

4 Answers4

17

I think you can do

(replace-regexp-in-string "\n$" "" 
              (shell-command-to-string "git rev-parse --show-toplevel"))
slitvinov
  • 5,693
  • 20
  • 31
10

If you only want to remove a newline at the very end of the output, use

(replace-regexp-in-string "\n\\'" "" 
  (shell-command-to-string "git rev-parse --show-toplevel"))

The accepted answer also replaces pairs of newlines ("\n\n") in the output by single newlines ("\n"), because $ matches at the end of the string or after a newline, while \\' only matches at the end of the string.

Clément
  • 12,299
  • 15
  • 75
  • 115
5

Assuming it is stored in a variable output-string, the final newline at the end can be removed this way:

(substring output-string 0 -1)

With the shell-command way, it would look like this:

(substring
  (shell-command-to-string "git rev-parse --show-toplevel")
  0 -1)
2

If You are OK with awesome external package.

use s-trim

ELISP> (shell-command-to-string "light -G")
"60.00\n"

ELISP> (s-trim (shell-command-to-string "light -G"))
"60.00"
azzamsa
  • 1,805
  • 2
  • 20
  • 28