Emacs Lisp: Getting Command Line Arguments

Perm url with updates: http://xahlee.org/emacs/elisp_command_line_argv.html

Emacs Lisp: Getting Command Line Arguments

Xah Lee, 2011-07-22

Remember, that elisp scripts can be run from the OS's command line. Like this:

emacs --script process_log.el

(For detail, see: Text Processing with Emacs Lisp Batch Style.)

Sometimes you want to pass a argument. For example, like this:

emacs --script process_log.el ~/weblog.txt

In your elisp script, you can get the argument from the builtin variable “argv”. The “argv” is a alias to “command-line-args-left”. Its value is a list. Each element is a unprocessed item from the command line. The complete command line items, including emacs invocation and any option passed to emacs (e.g. your script name) is stored in “command-line-args”.

Here's a sample test script:

;; -*- coding: utf-8 -*-
;; emacs lisp
;; 2011-07
;; a test script. getting arguments from command line

(message "Index 0: %S" (elt argv 0)) ; %S is for lisp code (aka sexp, s-expression)
(message "Index 1: %S" (elt argv 1))
(message "Index 2: %S" (elt argv 2))
(message "Index 3: %S" (elt argv 3))

(message "Whole value of argv: %S" argv) ; “argv” is same as “command-line-args-left”
(message "Whole value of command-line-args: %S" command-line-args)

If you save and name the above as “xx.el” and run it like this:

emacs --script xx.el uni 2 -tri

Here's the output:

$ emacs --script xx.el uni 2 -tri
Index 0: "uni"
Index 1: "2"
Index 2: "-tri"
Index 3: nil
Whole value of argv: ("uni" "2" "-tri")
Whole value of command-line-args: ("emacs" "-scriptload" "xx.el" "uni" "2" "-tri")
Unknown option `-tri'

(info "(elisp) Command-Line Arguments")

2011-07-22 Thanks to Piotr Chamera 〔piotr_cham…@poczta.onet.pl〕, Swami Tota Ram Shankar 〔tota_…@india.com〕.

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs