Last active
October 23, 2024 16:57
-
-
Save jamescherti/8d080423fe0119b71563058bc2fd3855 to your computer and use it in GitHub Desktop.
Emacs Lisp: Return the first line of output from executing COMMAND.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; shell-command-first-line-to-string.el --- Return the first line of output from executing COMMAND. -*- lexical-binding: t; -*- | |
;; Return the first line of output from executing COMMAND. | |
;; If the command fails or produces no output, return nil. | |
;; | |
;; This function is superior to `shell-command-to-string` because it allows | |
;; for the detection of command execution failures by examining the exit status. | |
;; While `shell-command-to-string` only returns the output as a string, | |
;; it does not provide information about whether the command succeeded or failed. | |
;; By using `call-process-shell-command`, this function can capture both | |
;; the output and the exit status, enabling better error handling | |
;; and more robust command execution. | |
;; | |
;; Gits URL: https://gist.github.com/jamescherti/8d080423fe0119b71563058bc2fd3855 | |
;; License: MIT | |
;; Author: James Cherti | |
(defun my-shell-command-first-line-to-string (command) | |
"Return the first line of output from executing COMMAND. | |
If the command fails or produces no output, return nil. | |
This function is superior to `shell-command-to-string` because it allows | |
for the detection of command execution failures by examining the exit status. | |
While `shell-command-to-string` only returns the output as a string, | |
it does not provide information about whether the command succeeded or failed. | |
By using `call-process-shell-command`, this function can capture both | |
the output and the exit status, enabling better error handling | |
and more robust command execution." | |
;; Generate a unique output buffer | |
(let ((output-buffer (generate-new-buffer | |
"*my-shell-command-first-line-to-string*"))) | |
(unwind-protect | |
(progn | |
(let ((exit-status (call-process-shell-command command | |
nil | |
output-buffer))) | |
(when (eq exit-status 0) | |
(with-current-buffer output-buffer | |
(goto-char (point-min)) | |
;; Get the first line as plain text without properties | |
(let ((first-line (buffer-substring-no-properties | |
(point) | |
(line-end-position)))) | |
(when (not (string-empty-p first-line)) | |
(string-trim-right first-line "\n"))))))) | |
;; Ensure the output buffer is killed after use | |
(kill-buffer output-buffer)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment