ZetCode

Scheme command-line arguments

last modified November 25, 2026 Guile 3.0

A program started from a shell receives its command-line arguments: the words typed after the program name. They let the user choose a file, a number, or a mode of operation without changing the source code. This article reads the arguments, turns them into numbers, reports errors through the exit status, and parses options, first by hand and then with the getopt-long module that ships with GNU Guile. The examples run with GNU Guile 3.0.7.

Listing the arguments

The command-line procedure returns the arguments as a list of strings. The first element is the name of the script as it was typed; the rest are the arguments that follow it.

args.scm
(define args (command-line))

(display "program: ")
(display (car args))
(newline)
(display "arguments: ")
(display (length (cdr args)))
(newline)

(for-each (lambda (arg)
            (display "  ")
            (write arg)
            (newline))
          (cdr args))

The program prints the script name, counts the remaining elements, and writes each argument with write, so the quotes show where an argument starts and ends. The shell splits the line at spaces, unless a part is quoted, and passes every argument as a string, including 42. Guile stops reading its own options at the script name, so everything after args.scm belongs to the program. Guile also provides program-arguments, which returns the same list.

$ guile args.scm red "light green" 42
program: args.scm
arguments: 3
  "red"
  "light green"
  "42"
$ guile args.scm
program: args.scm
arguments: 0

Arguments are strings

An argument that stands for a number has to be converted with string->number, which returns #f for text that is not a number. This program adds up its arguments and skips those that cannot be converted.

sum.scm
(define (parse-numbers args)
  (let loop ((args args) (acc '()))
    (cond ((null? args) (reverse acc))
          ((string->number (car args))
           => (lambda (n) (loop (cdr args) (cons n acc))))
          (else
           (display "not a number: ")
           (display (car args))
           (newline)
           (loop (cdr args) acc)))))

(define numbers (parse-numbers (cdr (command-line))))

(display (length numbers))
(display " numbers, sum ")
(display (apply + numbers))
(newline)

parse-numbers walks the arguments with a named let. The => clause of cond passes the converted number to the lambda, so each argument is converted only once. An argument that is not a number is reported and left out. Because string->number reads Scheme syntax, the user can also type fractions such as 1/2. The inexact 23.5 makes the whole sum inexact, so it prints as 43.0.

$ guile sum.scm 4 15 23.5 1/2
4 numbers, sum 43.0
$ guile sum.scm 10 ten 20
not a number: ten
2 numbers, sum 30

A default for a missing argument

Arguments are often optional. Before the program takes an element of the list, it checks that the element is there and uses a default value otherwise.

greet.scm
(define args (cdr (command-line)))

(define name
  (if (null? args) "stranger" (car args)))

(define times
  (if (and (pair? args) (pair? (cdr args)))
      (or (string->number (cadr args)) 1)
      1))

(do ((i 0 (+ i 1)))
    ((= i times))
  (display "Hello there, ")
  (display name)
  (display "!")
  (newline))

The first argument is a name and the second the number of greetings. (pair? (cdr args)) checks that there is a second element, and or falls back to 1 when it is not a number. Taking (cadr args) from a list that is too short would stop the program with an error, so the checks come first.

$ guile greet.scm
Hello there, stranger!
$ guile greet.scm Peter 3
Hello there, Peter!
Hello there, Peter!
Hello there, Peter!
$ guile greet.scm Lucia many
Hello there, Lucia!

The exit status

A program tells the shell whether it succeeded with its exit status, a small integer where 0 means success. exit ends the program with the given status; (exit #t) and (exit) mean 0, and (exit #f) means 1. A program that runs to the end of the file exits with 0. Error messages go to the standard error, so they are not mixed with the results when the output is redirected.

power.scm
(define args (cdr (command-line)))

(define (fail message status)
  (display message (current-error-port))
  (newline (current-error-port))
  (exit status))

(unless (= (length args) 2)
  (fail "usage: guile power.scm BASE EXPONENT" 2))

(define base (string->number (car args)))
(define exponent (string->number (cadr args)))

(unless (and base exponent (exact-integer? exponent))
  (fail "error: BASE must be a number and EXPONENT an integer" 1))

(display (expt base exponent))
(newline)

fail prints a message to (current-error-port) and exits with the given status. A wrong number of arguments is a usage error and returns 2, the convention of many Unix tools; arguments that are not numbers return 1. Since exit does not return, the code after each check runs only when the check has passed. The shell variable $? holds the status of the last command.

$ guile power.scm 2 100
1267650600228229401496703205376
$ echo $?
0
$ guile power.scm 2
usage: guile power.scm BASE EXPONENT
$ echo $?
2
$ guile power.scm two 3.5
error: BASE must be a number and EXPONENT an integer
$ echo $?
1

Options by hand

Arguments that begin with a dash are usually options, which switch a feature on, while the other arguments are data. A simple program can sort them out itself.

flags.scm
(define (option? arg)
  (and (> (string-length arg) 1)
       (char=? (string-ref arg 0) #\-)))

(define upper #f)
(define numbered #f)
(define words '())

(for-each (lambda (arg)
            (cond ((not (option? arg))
                   (set! words (append words (list arg))))
                  ((member arg '("-u" "--upper")) (set! upper #t))
                  ((member arg '("-n" "--number")) (set! numbered #t))
                  (else
                   (display "unknown option: " (current-error-port))
                   (display arg (current-error-port))
                   (newline (current-error-port))
                   (exit 2))))
          (cdr (command-line)))

(let loop ((words words) (n 1))
  (unless (null? words)
    (when numbered
      (display n)
      (display ". "))
    (display (if upper (string-upcase (car words)) (car words)))
    (newline)
    (loop (cdr words) (+ n 1))))

option? treats an argument as an option when it starts with a dash and has at least two characters. Every option has a short and a long form, checked with member. -u converts the words to upper case and -n numbers them; options may appear anywhere between the words. An unknown option is a usage error. The approach soon gets tedious: the program does not understand combined options such as -un, and options that take a value would need more code.

$ guile flags.scm -n apple pear --upper plum
1. APPLE
2. PEAR
3. PLUM
$ guile flags.scm -x apple
unknown option: -x
$ echo $?
2

The getopt-long module

The (ice-9 getopt-long) module parses options from a specification. Each entry names a long option and lists its properties: single-char gives the short form, and (value #t) says the option takes a value. getopt-long returns an association list of the options found, and option-ref reads one of them with a default.

options.scm
(use-modules (ice-9 getopt-long))

(define spec
  '((upper  (single-char #\u))
    (number (single-char #\n))
    (prefix (single-char #\p) (value #t))
    (help   (single-char #\h))))

(define options (getopt-long (command-line) spec))

(when (option-ref options 'help #f)
  (display "usage: guile options.scm [-u] [-n] [-p PREFIX] WORD...")
  (newline)
  (exit 0))

(define upper (option-ref options 'upper #f))
(define numbered (option-ref options 'number #f))
(define prefix (option-ref options 'prefix ""))
(define words (option-ref options '() '()))

(let loop ((words words) (n 1))
  (unless (null? words)
    (display prefix)
    (when numbered
      (display n)
      (display ". "))
    (display (if upper (string-upcase (car words)) (car words)))
    (newline)
    (loop (cdr words) (+ n 1))))

The program prints its words like the previous example and adds a prefix option with a value. An option without a value is #t when it was given. The empty list '() is the key of the remaining arguments. getopt-long accepts combined short options (-un), long options with = or with a separate value, and --, after which everything is data. An unknown option ends the program with a message and status 1.

$ guile options.scm -un apple pear
1. APPLE
2. PEAR
$ guile options.scm --prefix="* " -n apple pear
* 1. apple
* 2. pear
$ guile options.scm -h
usage: guile options.scm [-u] [-n] [-p PREFIX] WORD...
$ guile options.scm --colour red apple
options.scm: no such option: --colour
$ echo $?
1

Required options and checks

An entry can also contain (required? #t), which makes the option mandatory, and a predicate, a procedure that checks the value. The predicate is a procedure, not data, so the specification is built with quasiquote and the procedure is inserted with a comma.

grid.scm
(use-modules (ice-9 getopt-long))

(define (positive-integer? text)
  (let ((n (string->number text)))
    (and n (exact-integer? n) (positive? n))))

(define spec
  `((count (single-char #\c) (value #t) (required? #t)
           (predicate ,positive-integer?))
    (columns (single-char #\k) (value #t)
             (predicate ,positive-integer?))))

(define options (getopt-long (command-line) spec))
(define total (string->number (option-ref options 'count #f)))
(define columns (string->number (option-ref options 'columns "5")))

(do ((i 1 (+ i 1)))
    ((> i total))
  (display i)
  (display (if (or (= (remainder i columns) 0) (= i total))
               "\n"
               " ")))

The program prints the numbers from 1 to the --count value in rows of --columns numbers. positive-integer? accepts only whole numbers greater than zero. Because getopt-long has already checked the values, the program can convert them without testing for #f. A missing required option and a value that fails the predicate are reported by getopt-long itself.

$ guile grid.scm -c 10 -k 4
1 2 3 4
5 6 7 8
9 10
$ guile grid.scm --count=7
1 2 3 4 5
6 7
$ guile grid.scm
grid.scm: option must be specified: --count
$ echo $?
1
$ guile grid.scm -c ten
grid.scm: option predicate failed: --count

A main procedure

Larger programs often keep their code in procedures and start from a single main procedure. Guile's -e switch names the procedure to call after the file is loaded; it receives the command line as its argument. With the shebang line, a script can also be run as a command.

greeter.scm
#!/usr/bin/env -S guile -e main -s
!#

(define (main args)
  (let ((names (cdr args)))
    (when (null? names)
      (display "usage: greeter.scm NAME..." (current-error-port))
      (newline (current-error-port))
      (exit 1))
    (for-each (lambda (name)
                (display "Hello there, ")
                (display name)
                (newline))
              names)))

The first line tells the system to start guile -e main -s with the file name, and the !# line ends a block comment that Guile's reader opened at #!. The -S option of env splits the switches into separate arguments. The return value of main is ignored, so the exit status is set with exit. After chmod +x the script runs like any other command; it can still be started with guile directly.

$ chmod +x greeter.scm
$ ./greeter.scm Jan Lucia
Hello there, Jan
Hello there, Lucia
$ guile -e main -s greeter.scm Eva
Hello there, Eva
$ ./greeter.scm
usage: greeter.scm NAME...
$ echo $?
1

A word counting tool

The last example puts the parts together into a small version of the Unix wc tool. It counts the lines and words of the files given on the command line, and the -l and -w options select what to print.

counter.scm
(use-modules (ice-9 getopt-long) (ice-9 rdelim)
             (ice-9 exceptions) (ice-9 format))

(define spec
  '((lines (single-char #\l))
    (words (single-char #\w))))

(define (count-words line)
  (length (filter (lambda (word) (not (string-null? word)))
                  (string-split line #\space))))

(define (file-counts file)
  (call-with-input-file file
    (lambda (port)
      (let loop ((line (read-line port)) (lines 0) (words 0))
        (if (eof-object? line)
            (list lines words)
            (loop (read-line port) (+ lines 1)
                  (+ words (count-words line))))))))

(define (report-error file e)
  (format (current-error-port) "~a: ~a~%"
          file (car (exception-irritants e))))

(define options (getopt-long (command-line) spec))
(define show-lines (option-ref options 'lines #f))
(define show-words (option-ref options 'words #f))
(define show-both (not (or show-lines show-words)))
(define status 0)

(for-each
 (lambda (file)
   (guard (e ((error? e)
              (report-error file e)
              (set! status 1)))
     (let ((counts (file-counts file)))
       (when (or show-both show-lines)
         (format #t "~d " (car counts)))
       (when (or show-both show-words)
         (format #t "~d " (cadr counts)))
       (format #t "~a~%" file))))
 (option-ref options '() '()))

(exit status)

file-counts reads a file line by line and returns a list of the line and word counts; count-words splits a line at spaces and ignores the empty strings that repeated spaces leave behind. Without options both counts are printed. A file that cannot be opened is reported with the message of the operating system, the program continues with the next file, and the exit status becomes 1, as with wc.

$ cat notes.txt
buy bread
call the  plumber
  water the plants

return library books
$ guile counter.scm poem.txt notes.txt
4 25 poem.txt
5 11 notes.txt
$ guile counter.scm -l poem.txt missing.txt notes.txt
4 poem.txt
missing.txt: No such file or directory
5 notes.txt
$ echo $?
1

Source

Runtime Environment — GNU Guile Reference Manual

getopt-long — GNU Guile Reference Manual

The Meta Switch — GNU Guile Reference Manual

In this article we have read the command-line arguments with command-line, converted them to numbers, supplied defaults, reported errors through the exit status, parsed options by hand and with getopt-long, required and checked option values, started a program from a main procedure, and written a small word counting tool. The files article covers the file reading used by the tool, and the quasiquote article the syntax that builds the option specification.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.