Command Line Arguments in Lisp

Command-line arguments are a common way to parameterize execution of programs. For example, sbcl --script hello.lisp uses --script and hello.lisp arguments to the sbcl program.

(defun main ()
  ;; sb-ext:*posix-argv* provides access to raw command-line
  ;; arguments. Note that the first value in this list
  ;; is the path to the program, and (rest sb-ext:*posix-argv*)
  ;; holds the arguments to the program.
  (let ((args-with-prog sb-ext:*posix-argv*)
        (args-without-prog (rest sb-ext:*posix-argv*)))
    
    ;; You can get individual args with normal indexing.
    (let ((arg (nth 3 sb-ext:*posix-argv*)))
      
      (format t "~A~%" args-with-prog)
      (format t "~A~%" args-without-prog)
      (format t "~A~%" arg))))

(main)

To experiment with command-line arguments it’s best to save the code in a file (e.g., command-line-arguments.lisp) and run it with SBCL:

$ sbcl --script command-line-arguments.lisp a b c d
(/path/to/sbcl --script command-line-arguments.lisp a b c d)
(a b c d)
d

Next, we’ll look at more advanced command-line processing with option parsing libraries in Lisp.