2023-02-27

handling command-line arguments

there is the procedure program-arguments that gives a list of the arguments given to the executed file or script. the first argument by convention is the name of the executed script file

for command-line interfaces with option parsing i recommend args-fold (even better: (sph cli), which is based on args-fold), it is powerful and fun to use. for how to use args-fold see the example below

there is also getopt-long with less capabilities

program-arguments example

here is an example of something that is possible. it binds the list of script arguments to variables

in a file named test

#!/usr/bin/guile
!#

(apply
  (lambda* (path #:optional target)
    #t)
  (cdr (program-arguments)))
chmod +x test
./test

args-fold usage example

(import (srfi srfi-37))
(define (unnamed-processor a result) (cons a result))
(define (unrecognized-processor opt name a result) (throw (quote unsupported-option) opt name))

(define (help-processor opt name arg result)
  (display "usage: xy...\n")
  (exit 0))

(define (dry-run-processor opt name arg result)
  (cons (cons name #t) result))

(define arguments (cdr (program-arguments)))
(define result (list))

(define af-options
  ; option :: names is-required-arg is-optional-arg processor
  (list
    (option (list #\h "help") #f #f help-processor)
    (option (list "dry-run") #f #f dry-run-processor)))

(define parsed-options
  (args-fold arguments af-options unrecognized-processor unnamed-processor result))

(write parsed-options)
(newline)