Emacs Lisp: Getting Command Line Arguments

Advertise Here

,

This page shows you how to get command line argument's values in a emacs lisp batch script.

You can run emacs lisp scripts from the OS's command line just like Perl, Python, scripts. 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 script 〔process_log.el〕, you want to know the file name passed to it, the 〔~/weblog.txt〕. How to do that?

“argv” Variable Hold Arguments

Argument from the command line is stored in the built-in elisp variable “argv”. Its value is a list. Each element is a item from the command line. (note: The “argv” is a alias to “command-line-args-left”)

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”.

Sample Script

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")

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

blog comments powered by Disqus