ZetCode

Scheme environment and processes

last modified November 25, 2026 Guile 3.0

Every process runs in an environment, a set of named string variables such as HOME and LANG, which it inherits from the process that started it. A Scheme program can read and change these variables, start other programs, check how they ended, and exchange data with them through pipes. This article uses the procedures of GNU Guile 3.0.7, which follow the POSIX system calls closely. The command-line arguments article covers the exit status of the program itself.

Reading environment variables

getenv returns the value of a variable as a string, or #f when the variable is not set.

variables.scm
(define (show name)
  (display name)
  (display " = ")
  (write (getenv name))
  (newline))

(show "HOME")
(show "LANG")
(show "SCHEME_LEVEL")

show prints a variable name and writes its value, so strings appear in quotes and a missing variable shows as #f. In a shell, a variable can be set for a single command by writing the assignment before it; the second run sets SCHEME_LEVEL this way. The values of HOME and LANG depend on the user and the system.

$ guile variables.scm
HOME = "/home/user"
LANG = "en_US.UTF-8"
SCHEME_LEVEL = #f
$ SCHEME_LEVEL=3 guile variables.scm
HOME = "/home/user"
LANG = "en_US.UTF-8"
SCHEME_LEVEL = "3"

A setting with a default

Environment variables are a common way to configure a program without command-line options. The program should then work when the variable is missing or has an unusable value.

defaults.scm
(define (env-or name default)
  (or (getenv name) default))

(define (env-number name default)
  (let ((value (getenv name)))
    (or (and value (string->number value))
        default)))

(define greeting (env-or "GREETING" "Hello there"))
(define repeat (env-number "REPEAT" 1))

(do ((i 0 (+ i 1)))
    ((= i repeat))
  (display greeting)
  (newline))

env-or returns the value or a default, relying on or returning its first true argument. env-number also converts the value; when the variable is missing or string->number fails, and gives #f and the default is used. The value lots is not a number, so the greeting is printed once.

$ guile defaults.scm
Hello there
$ GREETING="Good morning" REPEAT=2 guile defaults.scm
Good morning
Good morning
$ REPEAT=lots guile defaults.scm
Hello there

Changing the environment

setenv sets a variable and unsetenv removes it. environ returns the whole environment as a list of strings of the form NAME=value. The changes affect the program itself and the processes it starts later, never the shell that started it.

environ.scm
(define (split-entry entry)
  (let ((i (string-index entry #\=)))
    (cons (substring entry 0 i)
          (substring entry (+ i 1)))))

(define (variables-with-prefix prefix)
  (filter (lambda (pair) (string-prefix? prefix (car pair)))
          (map split-entry (environ))))

(define (show-app-variables)
  (for-each (lambda (pair)
              (display (car pair))
              (display ": ")
              (display (cdr pair))
              (newline))
            (variables-with-prefix "APP_"))
  (display "--")
  (newline))

(show-app-variables)
(setenv "APP_COLOUR" "teal")
(unsetenv "APP_DEBUG")
(show-app-variables)

split-entry splits an entry at the first = into a pair; a value may contain more = signs, so only the first one counts. variables-with-prefix keeps the variables whose names start with APP_, a simple way to group the settings of one application. After setenv and unsetenv the list has changed. New variables are added at the end of the environment.

$ APP_MODE=test APP_DEBUG=1 guile environ.scm
APP_MODE: test
APP_DEBUG: 1
--
APP_MODE: test
APP_COLOUR: teal
--

Running a shell command

system passes a string to the shell /bin/sh, waits for the command to finish, and returns its status. The command inherits the environment and writes to the same terminal as the program.

shell.scm
(setenv "COLOUR" "teal")

(define (run command)
  (let ((status (system command)))
    (display "status ")
    (display status)
    (display ", exit value ")
    (display (status:exit-val status))
    (newline)))

(run "echo \"the child sees COLOUR=$COLOUR\"")
(run "test -d /tmp")
(run "exit 3")

The child shell sees the COLOUR variable that the program has set, and expands $COLOUR itself. The returned status is the raw value of the waitpid call, which packs the exit code and other information into one integer: an exit code of 3 becomes 768. status:exit-val extracts the exit code.

$ guile shell.scm
the child sees COLOUR=teal
status 0, exit value 0
status 0, exit value 0
status 768, exit value 3

Exit codes and signals

A process ends either with an exit code or because a signal killed it. In the second case, status:exit-val returns #f and status:term-sig returns the number of the signal.

signals.scm
(define (describe status)
  (cond ((status:exit-val status)
         => (lambda (code)
              (if (= code 0)
                  "succeeded"
                  (string-append "failed with code "
                                 (number->string code)))))
        ((status:term-sig status)
         => (lambda (signal)
              (string-append "killed by signal "
                             (number->string signal))))
        (else "stopped")))

(for-each (lambda (command)
            (let ((status (system command)))
              (display command)
              (display ": ")
              (display (describe status))
              (newline)))
          '("true" "exit 4" "kill -TERM $$" "no-such-command"))

describe tries both accessors with the => clause of cond. kill -TERM $$ makes the shell send signal 15 to itself. A command that does not exist is reported by the shell on the standard error, which appears in the terminal, and the shell exits with code 127.

$ guile signals.scm
true: succeeded
exit 4: failed with code 4
kill -TERM $$: killed by signal 15
sh: 1: no-such-command: not found
no-such-command: failed with code 127

Running a program without a shell

The shell is convenient, but it interprets spaces, quotes, $, *, and ; in the command string. When an argument comes from user data, such as a file name with a space, this leads to errors or worse. system* starts a program directly and passes each argument unchanged.

direct.scm
(system* "echo" "$HOME" "*.scm" "one;two")
(system* "printf" "[%s]\n" "two words" "three more words")

(define status (system* "ls" "no-such-file"))
(display "ls returned ")
(display (status:exit-val status))
(newline)

echo receives $HOME, *.scm, and one;two literally, since no shell expands them. printf gets two arguments that contain spaces and prints each of them in brackets. Like system, system* returns the status; ls exits with 2 when a file does not exist.

$ guile direct.scm
$HOME *.scm one;two
[two words]
[three more words]
ls: cannot access 'no-such-file': No such file or directory
ls returned 2

Reading the output of a process

To use the output of a program, a Scheme program connects to it with a pipe. open-pipe* from the (ice-9 popen) module starts a program like system* and returns a port; with OPEN_READ, the port reads what the program writes to its standard output. close-pipe waits for the program and returns its status.

reading.scm
(use-modules (ice-9 popen) (ice-9 rdelim))

(define (command-lines program . args)
  (let ((port (apply open-pipe* OPEN_READ program args)))
    (let loop ((line (read-line port)) (acc '()))
      (if (eof-object? line)
          (values (reverse acc)
                  (status:exit-val (close-pipe port)))
          (loop (read-line port) (cons line acc))))))

(define-values (towns status) (command-lines "sort" "towns.txt"))
(display towns)
(newline)

(define-values (counts status2) (command-lines "wc" "-l" "towns.txt"))
(display (car (string-split (car counts) #\space)))
(display " lines")
(newline)

(define-values (files status3) (command-lines "ls" "no-such-dir"))
(display (list files status3))
(newline)

command-lines runs a program, collects its output lines, and returns them together with the exit code as two values, which define-values binds. The first call sorts the town names with sort, the second takes the line count from the output of wc. The error message of ls goes to the standard error, which is not part of the pipe, so it appears in the terminal and the list of lines is empty. open-input-pipe is the shell variant: it takes a single command string, like system.

$ cat towns.txt
Bratislava
Kosice
Presov
Zilina
Nitra
$ guile reading.scm
(Bratislava Kosice Nitra Presov Zilina)
5 lines
ls: cannot access 'no-such-dir': No such file or directory
(() 2)

Writing to a process

With OPEN_WRITE, the port writes to the standard input of the program, whose output goes to the terminal. This hands work to an existing tool.

writing.scm
(use-modules (ice-9 popen) (ice-9 format))

(define scores
  '(("Eva" . 82) ("Tom" . 95) ("Ann" . 67) ("Bob" . 90)))

(define port (open-pipe* OPEN_WRITE "sort" "-k" "2" "-n" "-r"))

(for-each (lambda (entry)
            (format port "~a ~d~%" (car entry) (cdr entry)))
          scores)

(display "data sent to sort")
(newline)

(define status (close-pipe port))
(display "sort finished with ")
(display (status:exit-val status))
(newline)

The program sends names and scores to sort, which orders the lines numerically by the second field in reverse. sort must read all of its input before it prints anything, so its output appears only when close-pipe closes the port and signals the end of the data. That is why the message data sent to sort comes first.

$ guile writing.scm
data sent to sort
Tom 95
Bob 90
Eva 82
Ann 67
sort finished with 0

A command runner

The last example runs a list of commands, collects their exit codes, and prints a report, like a small test or build script. The program exits with 1 if any command failed, so it can be used by other scripts.

runner.scm
(use-modules (ice-9 format))

(define commands
  '(("test" "-f" "towns.txt")
    ("test" "-d" "towns.txt")
    ("grep" "-q" "Kosice" "towns.txt")
    ("ls" "missing.txt")
    ("sh" "-c" "exit 7")))

(define (run command)
  (let ((status (apply system* command)))
    (cons (string-join command " ")
          (status:exit-val status))))

(define results (map run commands))

(for-each (lambda (result)
            (format #t "~a ~a (~d)~%"
                    (if (zero? (cdr result)) "ok  " "FAIL")
                    (car result)
                    (cdr result)))
          results)

(define failed
  (filter (lambda (result) (not (zero? (cdr result)))) results))

(format #t "~d of ~d commands failed~%" (length failed) (length results))
(exit (if (null? failed) 0 1))

Each command is a list of strings passed to system* with apply, so no shell is involved. run returns a pair of the command text and its exit code, and the results are printed with format. The test and grep -q commands print nothing and report only through their exit codes. The message from ls comes first because the commands run before the report is printed.

$ guile runner.scm
ls: cannot access 'missing.txt': No such file or directory
ok   test -f towns.txt (0)
FAIL test -d towns.txt (1)
ok   grep -q Kosice towns.txt (0)
FAIL ls missing.txt (2)
FAIL sh -c exit 7 (7)
3 of 5 commands failed
$ echo $?
1

Source

Runtime Environment — GNU Guile Reference Manual

Processes — GNU Guile Reference Manual

Pipes — GNU Guile Reference Manual

In this article we have read and changed environment variables, given settings default values, run commands through the shell with system and directly with system*, decoded exit codes and signals, read from and written to other programs through pipes, and written a command runner. The command-line arguments article sets the exit status of a Scheme program, and the multiple values article explains define-values.

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.