[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Run terminal command with output in current buffer

From: Stefan Monnier
Subject: Re: Run terminal command with output in current buffer
Date: Fri, 16 Jul 2021 12:36:49 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/28.0.50 (gnu/linux)

>   (let ( (cmd-excl (read-from-minibuffer "exclude: "))
>          (cmd-incl (read-from-minibuffer "include: "))
>      (cmd-cnum (read-from-minibuffer "cnum: "))
>      (cmd-ptrn (read-from-minibuffer "pattern: "))
>      (cmd-dpth (read-from-minibuffer "dpth: "))
>       cmd )
>     (setq cmd-excl (concat " --exclude=\\*." cmd-excl))
>     (setq cmd-incl (concat " --include=\\*." cmd-incl))
>     (setq cmd-cnum (concat " -C " cmd-cnum))
>     (setq cmd (concat "grep -hir" cmd-excl cmd-incl
>               cmd-cnum " " cmd-ptrn " " cmd-dpth))
>     (message "%s" cmd)
>     (shell-command cmd (current-buffer))) )

I'd probably write this as something like:

    (let* ((cmd-excl (concat "--exclude=*."
                             (read-string "exclude: ")))
           (cmd-incl (concat "--include=*."
                             (read-string "include: ")))
           (cmd-cnum (read-string "cnum: "))
           (cmd-ptrn (read-string "pattern: "))
           (cmd-dpth (read-string "dpth: "))
           (cmd1 `("grep" "-hir" ,cmd-excl ,cmd-incl
                          "-C" ,cmd-cnum ,cmd-ptrn))
           (cmd (concat (mapconcat #'shell-quote-argument cmd1 " ")
                        " " cmd-depth)))
      (message "%s %s" cmd)
      (shell-command cmd (current-buffer))) )

Note the use of `read-string` (`read-from-minibuffer` is a low-level
function used to implement `read-string`, `read-number`, `read-buffer`,
`completing-read`, ...) and the use of `shell-quote-argument` to deal
with quoting those parts that need it.

I presumed that "dpth" is supposed to be a glob pattern, which is the
only place where you actually need the shell.  You could also use
`file-expand-wildcards` instead so you don't need a shell at all (and
hence don't need `shell-quote-argument` either) and can use
`call-process` instead of `shell-command` which stops you from worrying
about what happens if the users put a `|`, `;`, `$(cmd)`, or other fun
stuff in dpth.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]