As already explained, the newline is coming from the shell command output.
You can eliminate that by making the shell command format its output with printf
(which is portable and reliable when it comes to displaying newlines, unlike echo
).
(shell-command-to-string "printf %s \"$(pwd)\"")
Alternatively...
If you don't actually need to run the program via your shell, than another convenient option (suggested in the comments by another user, but never converted to an answer) is to use process-lines
, which starts the specific program directly via call-process
and (quoting the manual) "waits for it to finish, and returns its output as a list of strings. Each string in the list holds a single line of text output by the program; the end-of-line characters are stripped from each line."
So using that, you can simply take the first list item:
(car (process-lines "pwd"))
No shell is involved here but, as newlines are stripped, this approach can also resolve scenarios where you are obtaining unwanted trailing newlines from the program itself.
Note that using process-lines
to take a single line from a large amount of output would be inadvisable, as the entire output will be converted to a list regardless of how much of it you use, which could be very inefficient. If you can't tell the program to limit its output then it may be preferable to use the shell approach, as you can then pipe the program's output through head
.
pwd
, not Emacs. Also, you should usestring=
, orequal
for strings, noteq
. – npostavs Apr 27 '16 at 19:50pwd
as a simple example, but the newline gets added in other situations I have tested. For example, running a python script that returns a string value with no newline will have a newline added when run fromshell-command-to-string
. Also,cat
ing a file with only one line of text and no trailing newline will have the newline appended in theshell-command-to-string
output. – elethan Apr 27 '16 at 20:06shell-command-to-string
? Note that in a terminal the prompt following the output of most commands is on the line after the output, not on the same line as the last line of the output, indicating that there's a newline at the end. – Tyler Apr 27 '16 at 21:34eq
to compare two strings -- not unless they are the same lisp object. e.g.(eq "foo" "foo")
is comparing two different lisp objects, and is thereforenil
. – phils Apr 28 '16 at 02:24