* posix.texi (Pipes): Expand and clarify a bit. Describe port
[bpt/guile.git] / doc / ref / scheme-scripts.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
44fd0a72 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Guile Scripting
9@section Guile Scripting
10
11Like AWK, Perl, or any shell, Guile can interpret script files. A Guile
12script is simply a file of Scheme code with some extra information at
13the beginning which tells the operating system how to invoke Guile, and
14then tells Guile how to handle the Scheme code.
15
16@menu
17* The Top of a Script File:: How to start a Guile script.
18* Invoking Guile:: Command line options understood by Guile.
19* The Meta Switch:: Passing complex argument lists to Guile
20 from shell scripts.
21* Command Line Handling:: Accessing the command line from a script.
22* Scripting Examples::
23@end menu
24
25
26@node The Top of a Script File
27@subsection The Top of a Script File
28
29The first line of a Guile script must tell the operating system to use
30Guile to evaluate the script, and then tell Guile how to go about doing
31that. Here is the simplest case:
32
33@itemize @bullet
34
35@item
36The first two characters of the file must be @samp{#!}.
37
38The operating system interprets this to mean that the rest of the line
39is the name of an executable that can interpret the script. Guile,
40however, interprets these characters as the beginning of a multi-line
41comment, terminated by the characters @samp{!#} on a line by themselves.
42(This is an extension to the syntax described in R5RS, added to support
43shell scripts.)
44
45@item
46Immediately after those two characters must come the full pathname to
47the Guile interpreter. On most systems, this would be
48@samp{/usr/local/bin/guile}.
49
50@item
51Then must come a space, followed by a command-line argument to pass to
52Guile; this should be @samp{-s}. This switch tells Guile to run a
53script, instead of soliciting the user for input from the terminal.
54There are more elaborate things one can do here; see @ref{The Meta
55Switch}.
56
57@item
58Follow this with a newline.
59
60@item
61The second line of the script should contain only the characters
62@samp{!#} --- just like the top of the file, but reversed. The
63operating system never reads this far, but Guile treats this as the end
64of the comment begun on the first line by the @samp{#!} characters.
65
66@item
67The rest of the file should be a Scheme program.
68
69@end itemize
70
71Guile reads the program, evaluating expressions in the order that they
72appear. Upon reaching the end of the file, Guile exits.
73
74
75@node Invoking Guile
76@subsection Invoking Guile
44fd0a72 77@cindex invocation
07d83abe
MV
78
79Here we describe Guile's command-line processing in detail. Guile
80processes its arguments from left to right, recognizing the switches
81described below. For examples, see @ref{Scripting Examples}.
82
83@table @code
84
85@item -s @var{script} @var{arg...}
86Read and evaluate Scheme source code from the file @var{script}, as the
87@code{load} function would. After loading @var{script}, exit. Any
88command-line arguments @var{arg...} following @var{script} become the
89script's arguments; the @code{command-line} function returns a list of
90strings of the form @code{(@var{script} @var{arg...})}.
91
92@item -c @var{expr} @var{arg...}
93Evaluate @var{expr} as Scheme code, and then exit. Any command-line
94arguments @var{arg...} following @var{expr} become command-line arguments; the
95@code{command-line} function returns a list of strings of the form
96@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
97Guile executable.
98
99@item -- @var{arg...}
100Run interactively, prompting the user for expressions and evaluating
101them. Any command-line arguments @var{arg...} following the @code{--}
102become command-line arguments for the interactive session; the
103@code{command-line} function returns a list of strings of the form
104@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
105Guile executable.
106
fcb8ba8c
MV
107@item -L @var{directory}
108Add @var{directory} to the front of Guile's module load path. The
109given directories are searched in the order given on the command line
110and before any directories in the GUILE_LOAD_PATH environment
111variable. Paths added here are @emph{not} in effect during execution
112of the user's @file{.guile} file.
113
07d83abe
MV
114@item -l @var{file}
115Load Scheme source code from @var{file}, and continue processing the
116command line.
117
118@item -e @var{function}
119Make @var{function} the @dfn{entry point} of the script. After loading
120the script file (with @code{-s}) or evaluating the expression (with
121@code{-c}), apply @var{function} to a list containing the program name
122and the command-line arguments --- the list provided by the
123@code{command-line} function.
124
125A @code{-e} switch can appear anywhere in the argument list, but Guile
126always invokes the @var{function} as the @emph{last} action it performs.
127This is weird, but because of the way script invocation works under
128POSIX, the @code{-s} option must always come last in the list.
129
130The @var{function} is most often a simple symbol that names a function
131that is defined in the script. It can also be of the form @code{(@@
132@var{module-name} @var{symbol})} and in that case, the symbol is
133looked up in the module named @var{module-name}.
134
135@xref{Scripting Examples}.
136
137@item -ds
138Treat a final @code{-s} option as if it occurred at this point in the
139command line; load the script here.
140
141This switch is necessary because, although the POSIX script invocation
142mechanism effectively requires the @code{-s} option to appear last, the
143programmer may well want to run the script before other actions
144requested on the command line. For examples, see @ref{Scripting
145Examples}.
146
147@item \
148Read more command-line arguments, starting from the second line of the
149script file. @xref{The Meta Switch}.
150
151@item --emacs
152Assume Guile is running as an inferior process of Emacs, and use a
153special protocol to communicate with Emacs's Guile interaction mode.
154This switch sets the global variable use-emacs-interface to @code{#t}.
155
156This switch is still experimental.
157
158@item --use-srfi=@var{list}
159The option @code{--use-srfi} expects a comma-separated list of numbers,
160each representing a SRFI number to be loaded into the interpreter
161before starting evaluating a script file or the REPL. Additionally,
162the feature identifier for the loaded SRFIs is recognized by
163`cond-expand' when using this option.
164
165@example
166guile --use-srfi=8,13
167@end example
168
169@item --debug
170Start with the debugging evaluator and enable backtraces. Using the
171debugging evaluator will give you better error messages but it will
172slow down execution. By default, the debugging evaluator is only used
173when entering an interactive session. When executing a script with
174@code{-s} or @code{-c}, the normal, faster evaluator is used by default.
175
176@vnew{1.8}
177@item --no-debug
178Do not use the debugging evaluator, even when entering an interactive
179session.
180
181@item -h@r{, }--help
182Display help on invoking Guile, and then exit.
183
184@item -v@r{, }--version
185Display the current version of Guile, and then exit.
186
187@end table
188
189
190@node The Meta Switch
191@subsection The Meta Switch
192
193Guile's command-line switches allow the programmer to describe
194reasonably complicated actions in scripts. Unfortunately, the POSIX
195script invocation mechanism only allows one argument to appear on the
196@samp{#!} line after the path to the Guile executable, and imposes
197arbitrary limits on that argument's length. Suppose you wrote a script
198starting like this:
199@example
200#!/usr/local/bin/guile -e main -s
201!#
202(define (main args)
203 (map (lambda (arg) (display arg) (display " "))
204 (cdr args))
205 (newline))
206@end example
207The intended meaning is clear: load the file, and then call @code{main}
208on the command-line arguments. However, the system will treat
209everything after the Guile path as a single argument --- the string
210@code{"-e main -s"} --- which is not what we want.
211
212As a workaround, the meta switch @code{\} allows the Guile programmer to
213specify an arbitrary number of options without patching the kernel. If
214the first argument to Guile is @code{\}, Guile will open the script file
215whose name follows the @code{\}, parse arguments starting from the
216file's second line (according to rules described below), and substitute
217them for the @code{\} switch.
218
219Working in concert with the meta switch, Guile treats the characters
220@samp{#!} as the beginning of a comment which extends through the next
221line containing only the characters @samp{!#}. This sort of comment may
222appear anywhere in a Guile program, but it is most useful at the top of
223a file, meshing magically with the POSIX script invocation mechanism.
224
225Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
226@example
227#!/usr/local/bin/guile \
228-e main -s
229!#
230(define (main args)
231 (map (lambda (arg) (display arg) (display " "))
232 (cdr args))
233 (newline))
234@end example
235
236Suppose a user invokes this script as follows:
237@example
238$ /u/jimb/ekko a b c
239@end example
240
241Here's what happens:
242@itemize @bullet
243
244@item
245the operating system recognizes the @samp{#!} token at the top of the
246file, and rewrites the command line to:
247@example
248/usr/local/bin/guile \ /u/jimb/ekko a b c
249@end example
250This is the usual behavior, prescribed by POSIX.
251
252@item
253When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
254@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
255and @code{-s} from it, and substitutes them for the @code{\} switch.
256Thus, Guile's command line now reads:
257@example
258/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
259@end example
260
261@item
262Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
263file of Scheme code (treating the first three lines as a comment), and
264then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
265
266@end itemize
267
268
269When Guile sees the meta switch @code{\}, it parses command-line
270argument from the script file according to the following rules:
271@itemize @bullet
272
273@item
274Each space character terminates an argument. This means that two
275spaces in a row introduce an argument @code{""}.
276
277@item
278The tab character is not permitted (unless you quote it with the
279backslash character, as described below), to avoid confusion.
280
281@item
282The newline character terminates the sequence of arguments, and will
283also terminate a final non-empty argument. (However, a newline
284following a space will not introduce a final empty-string argument;
285it only terminates the argument list.)
286
287@item
288The backslash character is the escape character. It escapes backslash,
289space, tab, and newline. The ANSI C escape sequences like @code{\n} and
290@code{\t} are also supported. These produce argument constituents; the
291two-character combination @code{\n} doesn't act like a terminating
292newline. The escape sequence @code{\@var{NNN}} for exactly three octal
293digits reads as the character whose ASCII code is @var{NNN}. As above,
294characters produced this way are argument constituents. Backslash
295followed by other characters is not allowed.
296
297@end itemize
298
299
300@node Command Line Handling
301@subsection Command Line Handling
302
303@c This section was written and contributed by Martin Grabmueller.
304
305The ability to accept and handle command line arguments is very
306important when writing Guile scripts to solve particular problems, such
307as extracting information from text files or interfacing with existing
308command line applications. This chapter describes how Guile makes
309command line arguments available to a Guile script, and the utilities
310that Guile provides to help with the processing of command line
311arguments.
312
313When a Guile script is invoked, Guile makes the command line arguments
314accessible via the procedure @code{command-line}, which returns the
315arguments as a list of strings.
316
317For example, if the script
318
319@example
320#! /usr/local/bin/guile -s
321!#
322(write (command-line))
323(newline)
324@end example
325
326@noindent
327is saved in a file @file{cmdline-test.scm} and invoked using the command
328line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
329is
330
331@example
332("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
333@end example
334
335If the script invocation includes a @code{-e} option, specifying a
336procedure to call after loading the script, Guile will call that
337procedure with @code{(command-line)} as its argument. So a script that
338uses @code{-e} doesn't need to refer explicitly to @code{command-line}
339in its code. For example, the script above would have identical
340behaviour if it was written instead like this:
341
342@example
343#! /usr/local/bin/guile \
344-e main -s
345!#
346(define (main args)
347 (write args)
348 (newline))
349@end example
350
351(Note the use of the meta switch @code{\} so that the script invocation
352can include more than one Guile option: @xref{The Meta Switch}.)
353
354These scripts use the @code{#!} POSIX convention so that they can be
355executed using their own file names directly, as in the example command
356line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
357can also be executed by typing out the implied Guile command line in
358full, as in:
359
360@example
361$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
362@end example
363
364@noindent
365or
366
367@example
368$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
369@end example
370
371Even when a script is invoked using this longer form, the arguments that
372the script receives are the same as if it had been invoked using the
373short form. Guile ensures that the @code{(command-line)} or @code{-e}
374arguments are independent of how the script is invoked, by stripping off
375the arguments that Guile itself processes.
376
377A script is free to parse and handle its command line arguments in any
378way that it chooses. Where the set of possible options and arguments is
379complex, however, it can get tricky to extract all the options, check
380the validity of given arguments, and so on. This task can be greatly
381simplified by taking advantage of the module @code{(ice-9 getopt-long)},
382which is distributed with Guile, @xref{getopt-long}.
383
384
385@node Scripting Examples
386@subsection Scripting Examples
387
388To start with, here are some examples of invoking Guile directly:
389
390@table @code
391
392@item guile -- a b c
393Run Guile interactively; @code{(command-line)} will return @*
394@code{("/usr/local/bin/guile" "a" "b" "c")}.
395
396@item guile -s /u/jimb/ex2 a b c
397Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
398@code{("/u/jimb/ex2" "a" "b" "c")}.
399
400@item guile -c '(write %load-path) (newline)'
401Write the value of the variable @code{%load-path}, print a newline,
402and exit.
403
404@item guile -e main -s /u/jimb/ex4 foo
405Load the file @file{/u/jimb/ex4}, and then call the function
406@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
407
408@item guile -l first -ds -l last -s script
409Load the files @file{first}, @file{script}, and @file{last}, in that
410order. The @code{-ds} switch says when to process the @code{-s}
411switch. For a more motivated example, see the scripts below.
412
413@end table
414
415
416Here is a very simple Guile script:
417@example
418#!/usr/local/bin/guile -s
419!#
420(display "Hello, world!")
421(newline)
422@end example
423The first line marks the file as a Guile script. When the user invokes
424it, the system runs @file{/usr/local/bin/guile} to interpret the script,
425passing @code{-s}, the script's filename, and any arguments given to the
426script as command-line arguments. When Guile sees @code{-s
427@var{script}}, it loads @var{script}. Thus, running this program
428produces the output:
429@example
430Hello, world!
431@end example
432
433Here is a script which prints the factorial of its argument:
434@example
435#!/usr/local/bin/guile -s
436!#
437(define (fact n)
438 (if (zero? n) 1
439 (* n (fact (- n 1)))))
440
441(display (fact (string->number (cadr (command-line)))))
442(newline)
443@end example
444In action:
445@example
446$ fact 5
447120
448$
449@end example
450
451However, suppose we want to use the definition of @code{fact} in this
452file from another script. We can't simply @code{load} the script file,
453and then use @code{fact}'s definition, because the script will try to
454compute and display a factorial when we load it. To avoid this problem,
455we might write the script this way:
456
457@example
458#!/usr/local/bin/guile \
459-e main -s
460!#
461(define (fact n)
462 (if (zero? n) 1
463 (* n (fact (- n 1)))))
464
465(define (main args)
466 (display (fact (string->number (cadr args))))
467 (newline))
468@end example
469This version packages the actions the script should perform in a
470function, @code{main}. This allows us to load the file purely for its
471definitions, without any extraneous computation taking place. Then we
472used the meta switch @code{\} and the entry point switch @code{-e} to
473tell Guile to call @code{main} after loading the script.
474@example
475$ fact 50
47630414093201713378043612608166064768844377641568960512000000000000
477@end example
478
479Suppose that we now want to write a script which computes the
480@code{choose} function: given a set of @var{m} distinct objects,
481@code{(choose @var{n} @var{m})} is the number of distinct subsets
482containing @var{n} objects each. It's easy to write @code{choose} given
483@code{fact}, so we might write the script this way:
484@example
485#!/usr/local/bin/guile \
486-l fact -e main -s
487!#
488(define (choose n m)
489 (/ (fact m) (* (fact (- m n)) (fact n))))
490
491(define (main args)
492 (let ((n (string->number (cadr args)))
493 (m (string->number (caddr args))))
494 (display (choose n m))
495 (newline)))
496@end example
497
498The command-line arguments here tell Guile to first load the file
499@file{fact}, and then run the script, with @code{main} as the entry
500point. In other words, the @code{choose} script can use definitions
501made in the @code{fact} script. Here are some sample runs:
502@example
503$ choose 0 4
5041
505$ choose 1 4
5064
507$ choose 2 4
5086
509$ choose 3 4
5104
511$ choose 4 4
5121
513$ choose 50 100
514100891344545564193334812497256
515@end example
516
44fd0a72
KR
517
518@c Local Variables:
519@c TeX-master: "guile.texi"
520@c End: