我希望在Emacs中运行一个shell命令并将完整输出捕获到一个变量中。是否有办法做到这一点?例如,我想以以下方式设置hello-string
变量为"hello"
:
(setq hello-string (capture-stdout-of-shell-command "/bin/echo hello"))
函数capture-stdout-of-shell-command
是否存在,如果存在,它的真实名称是什么?
我有一个建议可以扩展Ise Wisteria的答案。尝试使用类似这样的代码:
(setq my_shell_output
(substring
(shell-command-to-string "/bin/echo hello")
0 -1))
这应该将字符串"hello"
设置为my_shell_output
的值,但是要干净利落。使用(substring)
可以消除当emacs调用shell命令时会出现的尾随\n
。它在Windows上运行的emacs中使我感到困扰,并且可能也会在其他平台上发生。
(defun my-shell-command-to-string (&rest cmd) (replace-regexp-in-string "\r?\n$" "" (shell-command-to-string (mapconcat 'identity cmd " "))))
- spacebat\\'
,而不是 $
。 - Clément-n
来停止输出结尾的换行符。例如,echo -n hello
。 - Chuan Ma(shell-command-to-string "/bin/echo hello 2>/dev/null")
组合使用时无法正常工作。有没有处理可能为空字符串的提示? - Marcin
(shell-command-to-string "/bin/echo hello 2>/dev/null")
)。 - Yorick Sijsling