开发者

In Emacs-lisp, what is the correct way to use call-process on an ls command?

I want to execute the following shell command in emacs-lisp:

ls -t ~/org *.txt | head -5

My attempt at the following:

(call-process "ls" nil t nil "-t" "~/org" "*.txt" "| head -5")

results in

ls: ~/org: No such file or directory
ls: *.txt: No such file or directory
ls: |head -5: No such file or director开发者_如何学Goy

Any help would be greatly appreciated.


The problem is that tokens like ~, *, and | aren't processed/expanded by the ls program. Since the tokens aren't processed, ls is look for a file or directory literally called ~/org, a file or directory literally called *.txt, and a file or directory literally called | head -5. Thus the error message you received about `No such file or directory".

Those tokens are processed/expanded by the shell (like Bourne shell /bin/sh or Bash /bin/bash). Technically, interpretation of the tokens can be shell-specific, but most shell interpret at least some of the same standard tokens the same way, e.g. | means connecting programs together end-to-end to almost all shells. As a counterexample, Bourne shell (/bin/sh) does not do ~ tilde/home-directory expansion.

If you want to get the expansions, you have to get your calling program to do the expansion itself like a shell would (hard work) or run your ls command in a shell (much easier):

/bin/bash -c "ls -t ~/org *.txt | head -5"

so

(call-process "/bin/bash" nil t nil "-c" "ls -t ~/org *.txt | head -5")

Edit: Clarified some issues, like mentioning that /bin/sh doesn't do ~ expansion.


Depending on your use case, if you find yourself wanting to execute shell commands and have the output made available in a new buffer frequently, you can also make use of the shell-command feature. In your example, it would look something like this:

(shell-command "ls -t ~/org *.txt | head -5")

To have this inserted into the current buffer, however, would require that you set current-prefix-arg manually using something like (universal-argument), which is a bit of a hack. On the other hand, if you just want the output someplace you can get it and process it, shell-command will work as well as anything else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜