Run multiline bash script from Emacs

I want to run the following bash script, which is stored in an Elisp line, not a file .sh, and then saves the shell output in a variable.

#!/bin/bash
IFS=: read -ra _dirs_in_path <<< "$PATH"

for _dir in "${_dirs_in_path[@]}"; do
    for _file in "${_dir}"/*; do
        [[ -x ${_file} && -f ${_file} ]] && printf '%s\n' "${_file##*/}"
    done
done

I was unable to run shell-commandin bash scripts consisting of several lines. Emacs and Long Shell team did not help me as compileand comint-runalso require teams rather than bash syntax.

How to run a complex bash script from Elisp?

+5
source share
3 answers

Multiline commands provide an excellent argument bash -cif you quote them in the same way as any other shell argument that may contain shell metacharacters, for example:

(setq my-command
      (concat "IFS=: read -ra dirs <<<\"$PATH\"\n"
              "for dir in ${dirs[@]}; do\n"
              " echo got dir \"$dir\"\n"
              "done\n"))

(shell-command (format "bash -c %s" (shell-quote-argument my-command)))
+6

, , , . :)

(defun example-multiline-shell-command ()
  (interactive)
  (with-temp-buffer
    (insert "#!/bin/bash
IFS=: read -ra _dirs_in_path <<< \"$PATH\"

for _dir in \"${_dirs_in_path[@]}\"; do
    for _file in \"${_dir}\"/*; do
        [[ -x ${_file} && -f ${_file} ]] && printf '%s\n' \"${_file##*/}\"
    done
done")
    (write-region (point-min) (point-max) "~/temp.sh")
    (shell-command "source ~/temp.sh" (current-buffer))
    (buffer-string)))

EDIT , FYI "${_dirs_in_path[@]}" , , .

+2

shell-command bash. , shell-command bash, PATH. : " \" script elisp, PATH. , *Shell Command Output*.

(let ((path "PATH='/usr/local/bin:/usr/bin:/bin'")
      (command "IFS=: read -ra _dirs_in_path <<< \"$PATH\"

for _dir in \"${_dirs_in_path[@]}\"; do
    for _file in \"${_dir}\"/*; do
        [[ -x ${_file} && -f ${_file} ]] && printf '%s\n' \"${_file##*/}\"
    done
done"))
  (shell-command (concat path ";" command)))

, compile bash.

PATH: (getenv "PATH") , , , X- ( xdm, gdm kdm) Xsession, emacs, GUI, bash. emacs --daemon cron, /etc/profile ~/.profile, Emacs PATH.

(. SO), , Emacs , PATH, .

0

All Articles