1XS(1) General Commands Manual XS(1)
2
3
4
6 xs - extensible shell
7
9 xs [-silevxnpodV] [-c command | file] [arguments]
10
12 Xs is a command interpreter and programming language which combines the
13 features of other Unix shells and the features of a functional program‐
14 ming language such as Scheme. Xs is a descendant of rc(1) and es(1);
15 the three implementations are similar in scope and style, but not com‐
16 patible with each other.
17
18 Xs is intended for use both as an interactive shell and a programming
19 language for scripts.
20
21 Xs is an extremely customizable language. The semantics can be altered
22 radically by redefining functions that are called to implement internal
23 operations. This manual page describes the default, initial configura‐
24 tion. See the section entitled Hook Functions for details on entry
25 points which can be redefined to give the shell extended semantics.
26
28 Xs is an interpreter which reads commands and executes them. The sim‐
29 plest form of command in xs is a sequence of words separated by white
30 space (space and tab) characters. A word is either a string or a pro‐
31 gram fragment (see below). The first word is the command to be exe‐
32 cuted; the remaining words are passed as arguments to that command. If
33 the first word is a string, it is a interpreted as the name of a pro‐
34 gram or shell function to run. If the name is the name of a shell
35 function, that function is executed. Otherwise, the name is used as
36 the name of an executable file. If the name begins with /, ./, or ../,
37 then it is used as the absolute path name of a file; if not, xs looks
38 for an executable file in the directories named by $path.
39
40 Commands are terminated by newline or semicolon (;). A command may
41 also be terminated by an ampersand (&), which causes the command to be
42 run in the background: the shell does not wait for the command to fin‐
43 ish before continuing execution. Background processes have an implicit
44 redirection of /dev/null as their standard input that may be overridden
45 by an explicit redirection.
46
47 Quoting
48 Xs gives several characters special meaning; special characters auto‐
49 matically terminate words. The following characters, along with space,
50 tab, and newline, are special:
51
52 # $ & ´ ( ) ; < > \ ^ ` { | }
53
54 The single quote (') prevents special treatment of any character other
55 than itself. Any characters between single quotes, including newlines,
56 backslashes, and control characters, are treated as an uninterpreted
57 string. A quote character itself may be quoted by placing two quotes
58 in a row. A single quote character is therefore represented by the
59 sequence ''''. The empty string is represented by ''. Thus:
60
61 echo 'What''s the plan, Stan?'
62
63 prints out
64
65 What's the plan, Stan?
66
67 The backslash (\) quotes the immediately following character, if it is
68 one of the special characters, except for newline. In addition, xs
69 recognizes backslash sequences similar to those used in C strings:
70
71 \a alert (bell)
72
73 \b backspace
74
75 \e escape
76
77 \f form-feed
78
79 \n newline
80
81 \r carriage return
82
83 \t tab
84
85 \xnn hexadecimal character nn, for n in {0..9, a..f, A..F}
86
87 \mnn octal character mnn, for m in {0..3} and n in {0..7}
88
89 \unnnn Unicode character nnnn, for n in {0..9, a..f, A..F}
90
91 \Unnnnnnnn
92 Unicode character nnnnnnnn, for n in {0..9, a..f, A..F}
93
94 The character escapes may be used with eval to create characters from
95 codepoints at runtime.
96
97 echo `{{ |cp| eval echo '\u'$cp} 01dd}
98
99 Comments
100 The number sign (#) begins a comment in xs. All characters up to but
101 not including the next newline are ignored.
102
103 Line continuation
104 A long logical line may be continued over several physical lines by
105 terminating each line (except the last) with a backslash (\). The
106 backslash-newline sequence is treated as a space. Note that line con‐
107 tinuation does not work in comments, where the backslash is treated as
108 part of the comment, and inside quoted strings, where the backslash and
109 newline are quoted.
110
111 Lists
112 The primary data structure in xs is the list, which is a sequence of
113 words. Parentheses are used to group lists. The empty list is repre‐
114 sented by (). Lists have no hierarchical structure; a list inside
115 another list is expanded so that the outer list contains all the ele‐
116 ments of the inner list. (This is the same as perl's "list interpola‐
117 tion".) Thus, the following are all equivalent:
118
119 one two three
120 (one two three)
121 ((one) () ((two three)))
122
123 Note that the null string, '', and the empty list, (), are two very
124 different things. Assigning the null string to variable is a valid
125 operation, but it does not remove its definition.
126
127 Since lists can span multiple lines without explicit line continua‐
128 tions, they are ideal for long commands. For example:
129
130 switch $x \
131 error { result 1 } \
132 warning { echo oops! } \
133 good { echo no problem }
134
135 switch $x (
136 error { result 1 }
137 warning { echo oops! }
138 good { echo no problem }
139 )
140
141 Finally, note that there are some uses of parentheses not following
142 ordinary list rules: in let/local/%closure bindings, and in assign‐
143 ments.
144
145 Concatenation
146 Two lists may be joined by the concatenation operator (^). A single
147 word is a list of length one, so
148
149 echo foo^bar
150
151 produces the output
152
153 foobar
154
155 For lists of more than one element, concatenation produces the cross
156 (Cartesian) product of the elements in both lists:
157
158 echo (a- b- c-)^(1 2)
159
160 produces the output
161
162 a-1 a-2 b-1 b-2 c-1 c-2
163
164 Variables
165 A list may be assigned to a variable, using the notation
166
167 var = list
168
169 Whitespace is required around the assignment operator; this allows it
170 to be treated as a normal string character. This is true also for
171 assignment in let-forms and the like. Any sequence of non-special
172 characters, except a sequence including only digits, may be used as a
173 variable name. Xs exports all user-defined variables into the environ‐
174 ment unless it is explicitly told not to.
175
176 The value of a variable is referenced with the notation:
177
178 $var
179
180 Any variable which has not been assigned a value returns the empty list
181 when referenced. In addition, multiple references are allowed:
182
183 a = foo
184 b = a
185 echo $$b
186
187 prints
188
189 foo
190
191 A variable's definition may be removed by assigning the empty list to a
192 variable:
193
194 var =
195
196 Multiple variables may be assigned with a single assignment statment.
197 The left hand side of the assignment operation consists of a list of
198 variables which are assigned, one by one, to the values in the list on
199 the right hand side. If there are more variables than values in the
200 list, the empty list is assigned to the remaining variables. If there
201 are fewer variables than elements in the list, the last variable is
202 bound to all the remaining list values.
203
204 For example,
205
206 (a b) = 1 2 3
207
208 has the same effect as
209
210 a = 1
211 b = 2 3
212
213
214 and
215
216 (a b c) = 1 2
217
218 is the same as
219
220 a = 1
221 b = 2
222 c =
223
224 Note that when assigning values to more than one variable, the list of
225 variables must be enclosed in parentheses.
226
227 For ``free careting'' (see below) to work correctly, xs must make cer‐
228 tain assumptions about what characters may appear in a variable name.
229 Xs assumes that a variable name consists only of alphanumeric charac‐
230 ters, percent (%), star (*), dash (-), and underscore (_). To refer‐
231 ence a variable with other characters in its name, quote the variable
232 name. Thus:
233
234 echo $'we$Irdriab!le'
235
236 A variable name produced by some complex operation, such as concatena‐
237 tion, should be enclosed in parentheses:
238
239 $(var)
240
241 Thus:
242
243 Good-Morning = Bonjour
244 Guten = Good
245 Morgen = Morning
246 echo $($Guten^-^$Morgen)
247
248 prints
249
250 Bonjour
251
252 Each element of the list in parentheses is treated as an independent
253 variable and expanded separately. Thus, given the above definitions,
254
255 echo $(Guten Morgen)
256
257 prints
258
259 Good Morning
260
261 To count the number of elements in a variable, use
262
263 $#var
264
265 This returns a single-element list with the number of elements in $var.
266
267 Subscripting
268 Variables may be indexed with the notation
269
270 $var(n)
271
272 where n is a list of integers or ranges. Subscript indexes are based
273 at one. The list of subscripts need not be in order or even unique.
274 Thus, if
275
276 a = one two three
277
278 then
279
280 echo $a(3 3 3)
281
282 prints
283
284 three three three
285
286 Subscript indices which refer to nonexistent elements expand to the
287 empty list. Thus, given the definition above
288
289 echo $a(3 1 4 1 5 9 2 6 5)
290
291 prints
292
293 three one one two
294
295 Subscript ranges are of the form lo...hi and refer to all the elements
296 between lo and hi. If lo is omitted, then 1 is used as a default
297 value; if hi is omitted, the length of the list is used. Thus
298
299 * = $*(2 ...)
300
301 removes the first element of *, similar to the effect of shift in rc(1)
302 or sh(1).
303
304 If lo is greater than hi, the elements in the result are listed from hi
305 to lo.
306
307 The notation $n, where n is an integer, is a shorthand for $*(n).
308 Thus, xs's arguments may be referred to as $1, $2, and so on.
309
310 Note that the list of subscripts may be given by any xs expression, so
311
312 $var(`{awk 'BEGIN{for(i=1;i<=10;i++)print i;exit }'})
313
314 returns the first 10 elements of $var.
315
316 Constructed variables, such as $(a$b), may not be subscripted.
317
318 Subscripted variables may not be used on the left-hand side of the
319 assignment operator.
320
321 Free Carets
322 Xs inserts carets (concatenation operators) for free in certain situa‐
323 tions, in order to save some typing on the user's behalf. For example,
324 the following are all equivalent:
325
326 cc -O -g -c malloc.c alloca.c
327 cc -^(O g c) (malloc alloca)^.c
328 opts=O g c; files=malloc alloca; cc -$opts $files.c
329
330 Xs inserts a free-caret between the ``-'' and $opts, as well as between
331 $files and .c. The rule for free carets is as follows: if a word or
332 keyword is immediately followed by another word, keyword, dollar-sign
333 or backquote without any intervening spaces, then xs inserts a caret
334 between them.
335
336 Flattened Lists
337 To create a single-element list from a multi-element list, with the
338 components space-separated, use
339
340 $^var
341
342 Flattening is useful when the normal list concatenation rules need to
343 be bypassed. For example, to append a single period at the end of
344 $path, use:
345
346 echo $^path.
347
348 Wildcard Expansion
349 Xs expands wildcards in filenames if possible. When the characters *,
350 [ or ? occur in an argument or command, xs looks at the argument as a
351 pattern for matching against files. (Contrary to the behavior some
352 other shells exhibit, xs will only perform pattern matching if a
353 metacharacter occurs unquoted and literally in the input. Thus,
354
355 foo = '*'
356 echo $foo
357
358 will always echo just a star. In order for non-literal metacharacters
359 to be expanded, an eval statement must be used in order to rescan the
360 input.)
361
362 Pattern matching occurs according to the following rules: a * matches
363 any number (including zero) of characters. A ? matches any single
364 character, and a [ followed by a number of characters followed by a ]
365 matches a single character in that class. The rules for character
366 class matching are the same as those for ed(1), with the exception that
367 character class negation is achieved with the tilde (~), not the caret
368 (^), since the caret already means something else in xs. The filename
369 component separator, slash (/), must appear explicitly in patterns. *
370 and ? do not match a dot character (.) at the beginning of a filename
371 component.
372
373 A tilde (~) as the first character of an argument is used to refer to
374 home directories. A tilde alone or followed by a slash (/) is replaced
375 by the value of $home, which is usually the home directory of the cur‐
376 rent user. A tilde followed by a username is replaced with the home
377 directory of that user, according to getpwent(3).
378
379 Pattern Matching
380 The tilde (~) operator is used in xs for matching strings against wild‐
381 card patterns. The command
382
383 ~ subject pattern pattern ...
384
385 returns a true value if and only if the subject matches any of the pat‐
386 terns. The matching follows the same rules as wildcard expansion,
387 except that slashes (/) are not considered significant, leading dots
388 (.) do not have to be matched explicitly, and home directory expansion
389 does not occur. Thus
390
391 ~ foo f*
392
393 returns zero (true), while
394
395 ~ (bar baz) f*
396
397 returns one (false). The null list is matched by the null list, so
398
399 ~ $foo ()
400
401 checks to see whether $foo is empty or not. This may also be achieved
402 by the test
403
404 ~ $#foo 0
405
406 Note that inside a ~ command xs does not match patterns against file
407 names, so it is not necessary to quote the characters *, [ and ?. How‐
408 ever, xs does expand the subject against filenames if it contains
409 metacharacters. Thus, the command
410
411 ~ * ?
412
413 returns true if any of the files in the current directory have a sin‐
414 gle-character name. Note that if the ~ command is given a list as its
415 first argument, then a successful match against any of the elements of
416 that list will cause ~ to return true. For example:
417
418 ~ (foo goo zoo) z*
419
420 is true.
421
422 Pattern Extraction
423 The double-tilde (~~) operator is used in xs for extracting the parts
424 of strings that match patterns. The command
425
426 ~~ subject pattern pattern ...
427
428 returns the parts of each matching subject which correspond to the
429 wildcards.
430
431 Each subject is checked in order against each pattern; if it matches
432 the pattern, the parts of the subject which matched each *, ?, or []
433 character range are extracted, and processing moves on to the next sub‐
434 ject. If the subject does not match, the next pattern is tried.
435
436 For example, the result of the extraction operation
437
438 ~~ (foo.c foo.x bar.h) *.[ch]
439
440 is the list (foo c bar h).
441
442 Arithmetic Substitution
443 A single list element can be formed from an infix arithmetical expres‐
444 sion like so:
445
446 `( expression )
447
448 The expression can use any of the +, -, *, /, and % operators, and use
449 variable substitution of the form $var. Variable names containing +,
450 -, *, /, or % are not allowed within an arithmetic expression.
451
452 Parentheses can be used in normal infix fashion to alter order of eval‐
453 uation. Absent parentheses, evaluation follows the usual precedence.
454
455 Numbers can be written as floating-point or integer, but are always
456 decimal. Scientific notation (e.g. 1.23e11) will be used to print very
457 large and small floating-point values, but is not allowed in literal
458 numbers.
459
460 Any arithmetic operation involving floats produces a float; any opera‐
461 tion with only integers produces an integer.
462
463 Integers have the behavior of the native platform's long. Floats have
464 the behavior of the native platform's double.
465
466 xs's floats are stored with limited (typically 6 signicant digits) pre‐
467 cision.
468
469 Command Substitution
470 A list may be formed from the output of a command by using backquote
471 substitution:
472
473 `{ command }
474
475 returns a list formed from the standard output of the command in
476 braces. The characters stored in the variable $ifs (for ``input field
477 separator'') are used to split the output into list elements. By
478 default, $ifs has the value space-tab-newline. The braces may be omit‐
479 ted if the command is a single word. Thus `ls may be used instead of
480 `{ls}. This last feature is useful when defining functions that expand
481 to useful argument lists. A frequent use is:
482
483 fn src { echo *.[chy] }
484
485 followed by
486
487 wc `src
488
489 (This will print out a word-count of all C and Yacc source files in the
490 current directory.)
491
492 In order to override the value of $ifs for a single command substitu‐
493 tion, use:
494
495 `` ifs-list { command }
496
497 $ifs will be temporarily ignored and the command's output will be split
498 as specified by the list following the double backquote. For example:
499
500 `` :\n {cat /etc/passwd}
501
502 splits up /etc/passwd into fields.
503
504 Return Values
505 The return value of a command is obtained with the construct
506
507 <={ command }
508
509 The return value of an external program is its exit status (which in
510 other shells can be found in special variables such as $? or $status),
511 as either a small integer or the name of signal. Thus
512
513 echo <={test -f /etc/motd} <={test -w /vmunix} <=a.out
514
515 might produce the output
516
517 0 1 sigsegv+core
518
519 along with any output or error messages from the programs.
520
521 If the command is a pipeline, <= lists the return value of each pro‐
522 gram.
523
524 Xs functions and primitives can produce ``rich return values,'' that
525 is, arbitrary lists as return values.
526
527 When return values are interpreted as truth values, an extension of the
528 normal shell conventions apply. If any element of a list is not equal
529 to ``0'' (or the empty string), that list is considered false.
530
531 The return value of an assignment operation is the assigned value.
532 Thus, b = <={a = 7} assigns the same value to both a and b.
533
534 Logical Operators
535 There are a number of operators in Xs which depend on the exit status
536 of a command.
537
538 command1 && command2
539
540 executes the first command and then executes the second command if and
541 only if the first command has a ``true'' return value.
542
543 command1 || command2
544
545 executes the first command and then executes the second command if and
546 only if the first command has a ``false'' return value.
547
548 ! command
549
550 inverts the truth value of the exit status of a command.
551
552 Relational Operators
553 Xs has the usual complement of relational operators. To avoid confusion
554 with redirection or assignment, the relops are spelled: :lt, :le, :gt,
555 :ge, :eq and :ne. The relational operators are built upon %cmp and
556 return a boolean value.
557
558 Input and output
559 The standard output of a command may be redirected to a file with
560
561 command > file
562
563 and the standard input may be taken from a file with
564
565 command < file
566
567 File descriptors other than 0 and 1 may be specified also. For exam‐
568 ple, to redirect standard error to a file, use:
569
570 command >[2] file
571
572 In order to duplicate a file descriptor, use >[n=m]. Thus to redirect
573 both standard output and standard error to the same file, use
574
575 command > file >[2=1]
576
577 To close a file descriptor that may be open, use >[n=]. For example,
578 to close file descriptor 7:
579
580 command >[7=]
581
582 In order to place the output of a command at the end of an already
583 existing file, use:
584
585 command >> file
586
587 If the file does not exist, then it is created.
588
589 To open a file for reading and writing, use the <> redirection opera‐
590 tor; for reading and appending, use <>>. Both of these operators use
591 file descriptor 0 (standard input) by default. Similarly, >< truncates
592 a file and opens it for reading and writing, and >>< opens a file for
593 reading and appending; these operators use file descriptor 1 by
594 default.
595
596 ``Here documents'' are supported as in sh(1) with the use of
597
598 command << 'eof-marker'
599
600 If the end-of-file marker is quoted, then no variable substitution
601 occurs inside the here document. Otherwise, every variable is substi‐
602 tuted by its space-separated-list value (see Flat Lists, below), and if
603 a ^ character follows a variable name, it is deleted. This allows the
604 unambiguous use of variables adjacent to text, as in
605
606 $variable^follow
607
608 To include a literal $ in a here document created with an unquoted end-
609 of-file marker, use $$.
610
611 Additionally, xs supports ``here strings'', which are like here docu‐
612 ments, except that input is taken directly from a string on the command
613 line. Its use is illustrated here:
614
615 cat <<< 'this is a here string' | wc
616
617 (This feature enables xs to export functions that use here documents.)
618
619 Subscripted and constructed variables are not supported in here docu‐
620 ments and here strings.
621
622 Pipes
623 Two or more commands may be combined in a pipeline by placing the ver‐
624 tical bar (|) between them. The standard output (file descriptor 1) of
625 the command on the left is tied to the standard input (file descriptor
626 0) of the command on the right. The notation |[n=m] indicates that
627 file descriptor n of the left process is connected to file descriptor m
628 of the right process. |[n] is a shorthand for |[n=0]. As an example,
629 to pipe the standard error of a command to wc(1), use:
630
631 command |[2] wc
632
633 The exit status of a pipeline is considered true if and only if every
634 command in the pipeline exits true.
635
636 Input/Output Substitution
637 Some commands, like cmp(1) or diff(1), take their input from named
638 files on the command line, and do not use standard input. It is conve‐
639 nient sometimes to build nonlinear pipelines so that a command like cmp
640 can read the output of two commands at once. Xs does it like this:
641
642 cmp <{command1} <{command2}
643
644 compares the output of the two commands. Note: on some systems, this
645 form of redirection is implemented with pipes, and since one cannot
646 lseek(2) on a pipe, commands that use lseek will hang. For example,
647 most versions of diff seek on their inputs.
648
649 Data can be sent down a pipe to several commands using tee(1) and the
650 output version of this notation:
651
652 echo hi there | tee >{sed 's/^/p1 /'} >{sed 's/^/p2 /'}
653
654 Program Fragments
655 Xs allows the intermixing of code with strings. A program fragment,
656 which is a group of commands enclosed in braces ({ and }), may be used
657 anywhere a word is expected, and is treated as an indivisible unit.
658 For example, a program fragment may be passed as an argument, stored in
659 a variable, or written to a file or pipe. If a program fragment
660 appears as the first word in a command, it is executed, and any argu‐
661 ments are ignored. Thus the following all produce the same output:
662
663 { echo hello, world }
664 { echo hello, world } foo bar
665 xs -c { echo hello, world }
666 x = { echo hello, world }; $x
667 echo { echo hello, world } | xs
668 echo { echo hello, world } > foo; xs < foo
669
670 Since program fragments in the first position in a command are exe‐
671 cuted, braces may be used as a grouping mechanism for commands. For
672 example, to run several commands, with output from all of them redi‐
673 rected to the same file, one can do
674
675 { date; ps agux; who } > snapshot
676
677 In addition, program fragments can continue across multiple physical
678 lines without explicit line continuations, so the above command could
679 also be written:
680
681 {
682 date
683 ps agux
684 who
685 } > snapshot
686
687 A lambda is a variant on a program fragment which takes arguments. A
688 lambda has the form
689
690 { | parameters | commands }
691
692 The parameters are one or more variable names, to which arguments of
693 the lambda are assigned while the commands are run. The first argument
694 is assigned to the first variable, the second to the second, and so on.
695 If there are more arguments than parameters, the last named variable is
696 assigned all the remaining arguments; if there are fewer, the parame‐
697 ters for which there are no arguments are bound to the empty list.
698
699 Lambdas, like other program fragments, can appear anywhere in a list.
700 A more complicated example in the same spirit:
701
702 { |cmd arg| $cmd $arg } { |*| echo $* } hi
703
704 This command executes a lambda which runs its first argument, named
705 cmd, using its second argument, named arg, as the argument for the
706 first. The first argument of this function is another lambda, seen
707 previously, and the second argument is the word hi.
708
709 These lambda expressions
710
711 { |a b c| echo $c $b $a } 1 2
712 { |a b c| echo $c $b $a } 1 2 3 4 5
713
714 produce this output:
715
716 2 1
717 3 4 5 2 1
718
719 Functions
720 A function in xs is introduced with the syntax
721
722 fn name { | parameters | commands }
723
724 If the function name appears as the first word of a command, the com‐
725 mands are run, with the named parameters bound to the arguments to the
726 function.
727
728 The similarity between functions and lambdas is not coincidental. A
729 function in xs is a variable of the form fn-name. If name for which
730 the appropriate fn- variable exists is found in the first position of a
731 command, the value of the variable is substituted for the first word.
732 The above syntax for creating functions is equivalent to the variable
733 assignment
734
735 fn-name = { | parameters | commands }
736
737 Functions may be deleted with the syntax
738
739 fn name
740
741 which is equivalent to the assignment
742
743 fn-name =
744
745 If, as the most common case, a function variable is bound to a lambda,
746 when the function is invoked, the variable $0 is bound (dynamically,
747 see below) to the name of the function.
748
749 Lambdas are just another form of code fragment, and, as such, can be
750 exported in the environment, passed as arguments, etc. The difference
751 between the two forms is that lambdas bind their arguments, while sim‐
752 ple brace-enclosed groups ignore theirs.
753
754 Local Variables
755 Variable assignments may be made local to a set of commands with the
756 local construct:
757
758 local (var = value; var = value ...) command
759
760 The command may be a program fragment, so for example:
761
762 local (path = /bin /usr/bin; ifs = ) {
763 ...
764 }
765
766 sets path to a minimal useful path and removes ifs for the duration of
767 one long compound command.
768
769 Local-bound variables are exported into the environment, and will
770 invoke appropriately named settor functions (see below).
771
772 Lexically Scoped Variables
773 In addition to local variables, xs supports a different form of tempo‐
774 rary variable binding, using let-bound, or ``lexically scoped,'' vari‐
775 ables. (Lexical scoping is the form of binding used by most compiled
776 programming languages, such as C or Scheme.) A lexically scoped vari‐
777 able is introduced with a let statement:
778
779 let (var = value; var = value ...) command
780
781 The "= value" can be left out with same effect as "var =".
782
783 All references to any of the variables defined in a let statement by
784 any code located lexically (that is, textually) within the command por‐
785 tion of the statement will refer to the let-bound variable rather than
786 any environment or local-bound variable; the immediate text of the let
787 statement is the complete extent of that binding. That is, lexically
788 bound variables surrounding code fragments follow those code fragments
789 around.
790
791 An example best shows the difference between let and local (also known
792 as ``dynamic'') binding: (note that ``; '' is xs's default prompt.)
793
794 ; x = foo
795 ; let (x = bar) {
796 echo $x
797 fn lexical { echo $x }
798 }
799 bar
800 ; local (x = baz) {
801 echo $x
802 fn dynamic { echo $x }
803 }
804 baz
805 ; lexical
806 bar
807 ; dynamic
808 foo
809 ;
810
811 Lexically bound variables are not exported into the environment, and
812 never cause the invocation of settor functions. Function (lambda)
813 parameters are lexically bound to their values.
814
815 For loops
816 The command
817
818 for var list { command }
819
820 Runs the command once for each element of the list, with the named
821 variable bound lexically to each element of the list, in order. Note
822 that if list consists of more than a single term, for example (a b c)
823 it must be parenthesized.
824
825 If multiple bindings are given in the for statement, the looping occurs
826 in parallel and stops when all lists are exhausted. When one list is
827 finished before the others, the corresponding variable is bound to the
828 empty list for the remaining iterations. Thus the loop
829
830 for i (a b c); j (x y) { echo $#i $i $#j $j}
831
832 produces the output
833
834 1 a 1 x
835 1 b 1 y
836 1 c 0
837
838 Settor Functions
839 A settor function is a variable of the form set-var, which is typically
840 bound to a lambda. Whenever a value is assigned to the named variable,
841 the lambda is invoked with its arguments bound to the new value. While
842 the settor function is running, the variable $0 is bound to the name of
843 the variable being assigned. The result of the settor function is used
844 as the actual value in the assignment.
845
846 For example, the following settor function is used to keep the shell
847 variables home and HOME synchronized.
848
849 set-HOME = { |*|
850 local (set-home = )
851 home = $*
852 result $*
853 }
854
855 This settor function is called when any assignment is made to the vari‐
856 able HOME. It assigns the new value to the variable home, but disables
857 any settor function for home to prevent an infinite recursion. Then it
858 returns its argument unchanged for use in the actual assignment to
859 HOME.
860
861 Settor functions do not apply to lexically bound variables.
862
863 Primitives
864 Primitives are internal xs operations that cannot or should not (for
865 reasons of performance) be written in the interpreter's language. The
866 set of primitives makes up the run-time library for xs.
867
868 Primitives can be used with the syntax
869
870 $&name
871
872 A primitive can be used anywhere a lambda is expected. The list of
873 primitives is returned as the result of the primitive $&primitives.
874
875 For details on specific primitives, see the section entitled PRIMITIVES
876 below.
877
878 Exceptions
879 Exceptions in xs are used for many forms of non-structured control
880 flow, notably error reporting, signals, and flow of control constructs
881 such as escape.
882
883 Exceptions are passed up the call chain to catching routines. A
884 catcher may decide to intercept an exception, retry the code that
885 caused the exception, or pass the exception along. There can only be
886 one exception raised at any time.
887
888 Exceptions are represented by lists. The first word of an exception
889 is, by convention, the type of exception being raised. The following
890 exceptions are known:
891
892 eof Raised by %parse when the end of input is reached.
893
894 error source message
895 A run-time error. Almost all shell errors are reported with the
896 error exception. The default interactive loop and the outermost
897 level of the interpreter catch this exception and print the mes‐
898 sage. Source is the name of the routine (typically a primitive)
899 which raised the error.
900
901 exit [return-code]
902 Exits xs with return-code, or with 0 if return-code is not spec‐
903 ified.
904
905 retry When raised from a signal catcher, causes the body of the catch
906 clause to be run again. If the cause of the caught signal is
907 not resolved, invoking retry will create an uninterruptible
908 loop.
909
910 signal signame
911 Raised when the shell itself receives a signal, and the signal
912 is listed in the variable signals. Signame is the name of the
913 signal that was raised.
914
915 See the builtin commands catch and throw for details on how to manipu‐
916 late exceptions.
917
919 Several variables are known to xs and are treated specially. Redefin‐
920 ing these variables can change interpreter semantics. Note that only
921 dynamically bound (top-level or local-bound) variables are interpreted
922 in this way; the names of lexically bound variables are unimportant.
923
924 * The argument list of xs. $1, $2, etc. are the same as $*(1),
925 $*(2), etc.
926
927 $0 Holds the value of argv[0] with which xs was invoked. Addition‐
928 ally, $0 is set to the name of a function for the duration of
929 the execution of that function, and $0 is also set to the name
930 of the file being interpreted for the duration of a . command.
931
932 apid The process ID of the last process started in the background.
933
934 history
935 The name of a file to which commands are appended as xs reads
936 them. The history builtin uses this file, if defined. To use an
937 external program (such as history(1)), delete or redefine the xs
938 history function. If history is not set (the default), then xs
939 does not append commands to any file.
940
941 home The current user's home directory, used in tilde (~) expansion,
942 as the default directory for the builtin cd command, and as the
943 directory in which xs looks to find its initialization file,
944 .xsrc, if xs has been started up as a login shell, and .xsin, if
945 xs is an interactive shell. Like path and PATH, home and HOME
946 are aliased to each other.
947
948 ifs The default input field separator, used for splitting up the
949 output of backquote commands for digestion as a list. The ini‐
950 tial value of ifs is space-tab-newline.
951
952 max-eval-depth
953 This sets a limit on how many levels deep the interpreter's
954 evaluation stack may become.
955
956 noexport
957 A list of variables which xs will not export. All variables
958 except for the ones on this list and lexically bound variables
959 are exported.
960
961 path This is a list of directories to search in for commands. The
962 empty string stands for the current directory. Note also that
963 an assignment to path causes an automatic assignment to PATH,
964 and vice-versa. If neither path nor PATH are set at startup
965 time, path assumes a default value suitable for your system.
966 This is typically /usr/ucb /usr/bin /bin ''.
967
968 pid The process ID of the currently running xs.
969
970 prompt This variable holds the two prompts (in list form) that xs
971 prints. $prompt(1) is printed before each command is read, and
972 $prompt(2) is printed when input is expected to continue on the
973 next line. (See %parse for details.)
974
975 xs sets $prompt to ('; ' '') by default. The reason for this is
976 that it enables an xs user to grab commands from previous lines
977 using a mouse, and to present them to xs for re-interpretation;
978 the semicolon prompt is simply ignored by xs. The null
979 $prompt(2) also has its justification: an xs script, when typed
980 interactively, will not leave $prompt(2)'s on the screen, and
981 can therefore be grabbed by a mouse and placed directly into a
982 file for use as a shell script, without further editing being
983 necessary.
984
985 signals
986 Contains a list of the signals which xs traps. Any signal name
987 which is added to this list causes that signal to raise an xs
988 exception. For example, to run some commands and make sure some
989 cleanup routine is called even if the user interrupts or discon‐
990 nects during the script, one can use the form:
991
992 local (signals = $signals sighup sigint) {
993 catch { |e|
994 cleanup
995 throw $e
996 } {
997 ...
998 }
999 }
1000
1001 A signal name prefixed by a hyphen (-) causes that signal to be
1002 ignored by xs and all of its child processes, unless one of them
1003 resets its handler. A signal prefixed by a slash (/) is ignored
1004 in the current shell, but retains default behavior in child pro‐
1005 cesses. In addition, the signal sigint may be preceeded by the
1006 prefix (.) to indicate that normal shell interrupt processing
1007 (i.e., the printing of an extra newline) occurs. By default xs
1008 starts up with the values
1009
1010 .sigint /sigquit /sigterm
1011
1012 in $signals; other values will be on the list if the shell
1013 starts up with some signals ignored.
1014
1015 The values of path and home are derived from the environment values of
1016 PATH and HOME if those values are present. This is for compatibility
1017 with other Unix programs, such as sh(1). $PATH is assumed to be a
1018 colon-separated list.
1019
1020 Also for compatibility, xs maintains the value of the SHLVL variable,
1021 creating it with a value of I if needed and incrementing the value when
1022 a new xs is spawned. Unlike the other variables in this section, the
1023 value of SHLVL has no influence upon the behavior of the interpreter.
1024
1026 xs internally rewrites much of the syntax presented thus far in terms
1027 of calls to shell functions. Most features of xs that resemble tradi‐
1028 tional shell features are included in this category. This rewriting
1029 occurs at parse time, as commands are recognized by the interpreter.
1030 The shell functions that are the results of rewriting are some of the
1031 hook functions documented below.
1032
1033 The following tables list all of the major rewriting which xs does,
1034 with the forms typically entered by the user on the left and their
1035 internal form on the right. There is no reason for the user to avoid
1036 using the right-hand side forms, except that they are usually less con‐
1037 venient. To see the internal form of a specific command, a user can
1038 run xs with the -n and -x options; when invoked in this way, the shell
1039 prints the internal form of its commands rather than executing them.
1040
1041 Control Flow
1042 ! cmd %not {cmd}
1043 cmd & %background {cmd}
1044 cmd1 ; cmd2 %seq {cmd1} {cmd2}
1045 cmd1 && cmd2 %and {cmd1} {cmd2}
1046 cmd1 || cmd2 %or {cmd1} {cmd2}
1047 fn name {|args| cmd} fn-^name = {|args| cmd}
1048
1049 Input/Output Commands
1050 cmd < file %open 0 file {cmd}
1051 cmd > file %create 1 file {cmd}
1052 cmd >[n] file %create n file {cmd}
1053 cmd >> file %append 1 file {cmd}
1054 cmd <> file %open-write 0 file {cmd}
1055 cmd <>> file %open-append 0 file {cmd}
1056 cmd >< file %open-create 1 file {cmd}
1057 cmd >>< file %open-append 1 file {cmd}
1058 cmd >[n=] %close n {cmd}
1059 cmd >[m=n] %dup m n {cmd}
1060 cmd << tag input tag %here 0 input {cmd}
1061 cmd <<< string %here 0 string {cmd}
1062 cmd1 | cmd2 %pipe {cmd1} 1 0 {cmd2}
1063 cmd1 |[m=n] cmd2 %pipe {cmd1} m n {cmd2}
1064 cmd1 >{ cmd2 } %writeto var {cmd2} {cmd1 $var}
1065 cmd1 <{ cmd2 } %readfrom var {cmd2} {cmd1 $var}
1066
1067 Expressions
1068 $#var <={%count $var}
1069 $^var <={%flatten ' ' $var}
1070 `{cmd args} <={%backquote <={%flatten '' $ifs} {cmd args}}
1071 ``ifs {cmd args} <={%backquote <={%flatten '' ifs} {cmd args}}
1072
1073 Relational Operators
1074 a :lt b {~ {%cmp a b} -1}
1075 a :le b {~ {%cmp a b} -1 0}
1076 a :gt b {~ {%cmp a b} 1}
1077 a :ge b {~ {%cmp a b} 1 0}
1078 a :eq b {~ {%cmp a b} 0}
1079 a :ne b {~ {%cmp a b} -1 1}
1080
1082 Builtin commands are shell functions that exist at shell startup time.
1083 Most builtins are indistinguishable from external commands, except that
1084 they run in the context of the shell itself rather than as a child
1085 process. Many builtins are implemented with primitives (see above).
1086
1087 Some builtin functions have names that begin with a percent character
1088 (%). These are commands with some special meaning to the shell, or are
1089 meant for use only by users customizing the shell. (This distinction
1090 is somewhat fuzzy, and the decisions about which functions have %-names
1091 are somewhat arbitrary.)
1092
1093 All builtins can be redefined and extended by the user.
1094
1095 Builtin Commands
1096 . [-einvx] file [args ...]
1097 Reads file as input to xs and executes its contents. The
1098 options are a subset of the invocation options for the shell
1099 (see below).
1100
1101 access [-n name] [-1e] [-rwx] [-fdcblsp] path ...
1102 Tests if the named paths are accessible according to the options
1103 presented. Normally, access returns zero (true) for files which
1104 are accessible and a printable error message (which evaluates as
1105 false, according to shell rules) for files which are not acces‐
1106 sible. If the -1 option is used, the name of the first file
1107 which the test succeeds for is returned; if the test succeeds
1108 for no file, the empty list is returned. However, if the -e
1109 option was used, access raises an error exception. If the -n
1110 option is used, the pathname arguments are treated as a list of
1111 directories, and the name option argument is used as a file in
1112 those directories (i.e., -n is used for path searching).
1113
1114 The default test is whether a file exists. These options change
1115 the test:
1116
1117 -r Is the file readable (by the current user)?
1118
1119 -w Is the file writable?
1120
1121 -x Is the file executable?
1122
1123
1124 -f Is the file a plain file?
1125
1126 -d Is the file a directory?
1127
1128 -c Is the file a character device?
1129
1130 -b Is the file a block device?
1131
1132 -l Is the file a symbolic link?
1133
1134 -s Is the file a socket?
1135
1136 -p Is the file a named pipe (FIFO)?
1137
1138 alias alias-name expansion...
1139 Define a new function, alias-name , which calls expansion The
1140 first command in expansion is replaced with it's whatis value to
1141 prevent recursion. This can be used to serve a somewhat similar
1142 purpose as in bash. For example, the following will force ls to
1143 use color, and make l be ls in long form, with color (due to
1144 previous alias):
1145
1146 alias ls ls --color=yes
1147 alias l ls -l
1148
1149 catch catcher body
1150 Runs body. If it raises an exception, catcher is run and passed
1151 the exception as an argument.
1152
1153 cd [directory]
1154 Changes the current directory to directory. With no argument,
1155 cd changes the current directory to $home.
1156
1157 dirs [-c]
1158 Displays the directory stack. (See pushd and popd.) With the -c
1159 option, clear the directory stack.
1160
1161 echo [-n] [--] args ...
1162 Prints its arguments to standard output, terminated by a new‐
1163 line. Arguments are separated by spaces. If the first argument
1164 is -n no final newline is printed. If the first argument is --,
1165 then all other arguments are echoed literally; this is used for
1166 echoing a literal -n.
1167
1168 escape lambda
1169 Run lambda with one argument, an escape block which when evalu‐
1170 ated will return to the point after this escape. This is more
1171 formally refered to as an escape continuation. In fact, it's
1172 behaviour is a simple subset of exceptions, and is implemented
1173 fairly simply using catch. Escape is useful to replace
1174 return/break like constructs; for example
1175
1176 fn f { escape { |fn-return| {
1177 ...; return 0;
1178 ...
1179 }}
1180
1181 will exit the function with result 0 when it reaches the return.
1182
1183 eval list
1184 Concatenates the elements of list with spaces and feeds the
1185 resulting string to the interpreter for rescanning and execu‐
1186 tion.
1187
1188 exec cmd
1189 Replaces xs with the given command. If the exec contains only
1190 redirections, then these redirections apply to the current shell
1191 and the shell does not exit. For example,
1192
1193 exec {>[2] err.out}
1194
1195 places further output to standard error in the file err.out.
1196 Unlike some other shells, xs requires that redirections in an
1197 exec be enclosed in a program fragment.
1198
1199 exit [status]
1200 Causes the current shell to exit with the given exit status. If
1201 no argument is given, zero (true) is used. (This is different
1202 from other shells, that often use the status of the last command
1203 executed.)
1204
1205 false Always returns a false (non-zero) return value.
1206
1207 forever cmd
1208 Runs the command repeatedly, until the shell exits or the com‐
1209 mand raises an exception. This is equivalent to a while {true}
1210 {cmd} loop except that forever does not catch any exceptions.
1211
1212 fork cmd
1213 Runs a command in a subshell. This insulates the parent shell
1214 from the effects of state changing operations such as cd and
1215 variable assignments. For example:
1216
1217 fork {cd ..; make}
1218
1219 runs make(1) in the parent directory (..), but leaves the shell
1220 in the current directory.
1221
1222 history [# | -c | -d # | -n | -y]
1223 Display or modify the history list. (See the history variable in
1224 SPECIAL VARIABLES.) With no options, the entire history list is
1225 displayed. A numeric option limits the display to the specified
1226 number of most recent entries. The -c option clears the history
1227 list, while -d # deletes the #'th history item. History record‐
1228 ing may temporarily be turned off and on with the -n and -y
1229 options. When history has been turned off using the -n option,
1230 it may only be turned back on using the -y option in the same
1231 shell; not in a subshell.
1232
1233 if [test then-action] [else else-action]
1234 Evaluates the command test. If the result is true, the command
1235 then is run and if completes. If the result of the test is
1236 false, the else command is run. The else-action doesn't require
1237 braces no matter the number of actions, so one can write code
1238 like:
1239
1240 ... } else if {~ $a $b} { ... }
1241
1242 Note that:
1243
1244 ...}
1245 else if {~ $a $b} { ... }
1246
1247 with the else on a separate line, will only work if the if-com‐
1248 mand has parentheses wrapping its body and else-statements.
1249
1250 jobs Display background job information.
1251
1252 limit [-h] [resource [value]]
1253 Similar to the csh(1) limit builtin, this command operates upon
1254 the resource limits of a process. With no arguments, limit
1255 prints all the current limits; with one argument, limit prints
1256 the named limit; with two arguments, it sets the named limit to
1257 the given value. The -h flag displays/alters the hard limits.
1258 The resources which can be shown or altered are cputime, file‐
1259 size, datasize, stacksize, coredumpsize and memoryuse. For
1260 example:
1261
1262 limit coredumpsize 0
1263
1264 disables core dumps.
1265
1266 The limit values must either be the word ``unlimited'' or a num‐
1267 ber with an optional suffix indicating units. For size limits,
1268 the suffixes k (kilobytes), m (megabytes), and g (gigabytes) are
1269 recognized. For time limits, s (seconds), m (minutes), and h
1270 (hours) are known; in addition, times of the form hh:mm:ss and
1271 mm:ss are accepted. See getrlimit(2) for details on resource
1272 limit semantics.
1273
1274 map action list
1275 Call action with a single argument for each element of list.
1276 Since lists auto-expand, list contains the rest of the arguments
1277 to the command. Returns the list of results of each action. If
1278 action returns a list, it is expanded inside into a new process
1279 group. This builtin is useful for making xs behave like a job-
1280 control shell in a hostile environment. One example is the NeXT
1281 Terminal program, which implicitly assumes that each shell it
1282 forks will put itself into a new process group. Note that the
1283 controlling tty for the process must be on standard error (file
1284 descriptor 2) when this operation is run.
1285
1286 omap action list
1287 Like map , but return the list of the outputs of action, in the
1288 same form as if `` '' action (i.e. with an empty input field
1289 separator list) were called.
1290
1291 popd cd into the directory on top of the directory stack and pop the
1292 stack. If the stack is empty (for example, if pushd has not
1293 been called), then stay in the current directory. Also displays
1294 the remaining stack.
1295
1296 printf format ...
1297 Print formatted text. Valid conversions are those of printf(3p),
1298 including floating-point conversions. Length modifiers are not
1299 supported. Backslash escapes in the format are not interpreted
1300 by printf.
1301
1302 pushd [dir]
1303 Add directory's absolute path onto the directory stack, cd into
1304 the directory and display the new stack. If dir is not provided
1305 and the stack is at least two deep, then alternate between the
1306 top two directories.
1307
1308 read Reads from standard input and returns either the empty list (in
1309 the case of end-of-file) or a single element string with up to
1310 one line of data, including possible redirections. This func‐
1311 tion reads one character at a time in order to not read more
1312 data out of a pipe than it should. The terminating newline (if
1313 present) is not included in the returned string.
1314
1315 result value ...
1316 Returns its arguments. This is xs's identity function.
1317
1318 While result may be used to return a lambda from a function, a
1319 closure associated with the function will not work. In other
1320 words, xs does not support upward funargs.
1321
1322 switch value [case1 action1]...[default-action]
1323 Go through the list of cases, testing if they are equal to
1324 value. The matching action of the first case which matches is
1325 executed.
1326
1327 throw exception arg ...
1328 Raise the named exception, passing all of the arguments to throw
1329 to the enclosing exception handler.
1330
1331 time cmd arg ...
1332 Prints, on the shell's standard error, the real, user, and sys‐
1333 tem time consumed by executing the command.
1334
1335 true Always returns a true (zero) return value.
1336
1337 umask [mask]
1338 Sets the current umask (see umask(2)) to the octal mask. If no
1339 argument is present, the current mask value is printed.
1340
1341 until test body
1342 Identical to while, except test is negated
1343
1344 unwind-protect body cleanup
1345 Runs body and, when it completes or raises an exception, runs
1346 cleanup.
1347
1348 var var ...
1349 Prints definitions of the named variables, suitable for being
1350 used as input to the shell.
1351
1352 vars [-vfs] [-epi]
1353 Prints all shell variables, functions, and settor functions (in
1354 a form suitable for use as shell input), which match the crite‐
1355 ria specified by the options.
1356
1357 -v variables (that are not functions or settor functions)
1358
1359 -f functions
1360
1361 -s settor functions
1362
1363
1364 -e exported values
1365
1366 -p private (not exported) values
1367
1368 -i internal (predefined and builtin) values
1369
1370
1371 -a all of the above
1372
1373 If none of -v, -f, or -s are specified, -v is used. If none of
1374 -e, -p, or -i are specified, -e is used.
1375
1376 wait [pid]
1377 Waits for the specified pid, which must have been started by xs.
1378 If no pid is specified, waits for any child process to exit.
1379
1380 whatis progam ...
1381 For each named program, prints the pathname, primitive, lambda,
1382 or code fragment which would be run if the program appeared as
1383 the first word of a command.
1384
1385 while test body
1386 Evaluates the test and, if it is true, runs the body and
1387 repeats.
1388
1389 Hook Functions
1390 A subset of the %-named functions are known as ``hook functions.'' The
1391 hook functions are called to implement some internal shell operations,
1392 and are available as functions in order that their values can be
1393 changed. Typically, a call to a hook function is from code generated
1394 by the syntactic sugar rewritings.
1395
1396 %and cmd ...
1397 Runs the commands in order, stopping after the first one that
1398 has a false return value. Returns the result of the last com‐
1399 mand run.
1400
1401 %append fd file cmd
1402 Runs the command with file descriptor fd set up to append to the
1403 file.
1404
1405 %background cmd
1406 Runs the command in the background. The shell variable apid
1407 contains the process ID of the background process, which is
1408 printed if the shell is interactive (according to %is-interac‐
1409 tive).
1410
1411 %backquote separator cmd
1412 Runs the command in a child process and returns its standard
1413 output as a list, separated (with the same rules used in %split)
1414 into elements according to separator.
1415
1416 %batch-loop
1417 Parses commands from the current input source and passes the
1418 commands to the function %dispatch, which is usually a dynami‐
1419 cally bound identifier. This function catches the exception eof
1420 which causes it to return. This function is invoked by the
1421 shell on startup and from the dot (.) and eval commands, when
1422 the input source is not interactive. (See also %interactive-
1423 loop.)
1424
1425 %close fd cmd
1426 Runs the command with the given file descriptor closed.
1427
1428 %cmp a b
1429 Compares its arguments and returns -1, 0 or 1 if a is respec‐
1430 tively less than, equal to or greater than b. If either argu‐
1431 ment is non-numeric, then the arguments are compared lexico‐
1432 graphically, honoring the locale's collation order.
1433
1434 The result is not defined for list arguments, except that com‐
1435 parisons may be made against the empty list. The result in this
1436 case is 0 if both arguments are either an empty list or an empty
1437 string, and nonzero otherwise.
1438
1439 %count list
1440 Returns the number of arguments to the primitive.
1441
1442 %create fd file cmd
1443 Runs the command with file descriptor fd set up to write to the
1444 file.
1445
1446 %dup newfd oldfd cmd
1447 Runs the command with the file descriptor oldfd copied (via
1448 dup(2)) to file descriptor newfd.
1449
1450 %eval-noprint cmd
1451 Run the command. (Passed as the argument to %batch-loop and
1452 %interactive-loop.)
1453
1454 %eval-print cmd
1455 Print and run the command. (Passed as the argument to %batch-
1456 loop and %interactive-loop when the -x option is used.)
1457
1458 %exec-failure file argv0 args ...
1459 This function, if it exists, is called in the context of a child
1460 process if an executable file was found but execve(2) could not
1461 run it. If the function returns, an error message is printed
1462 and the shell exits, but the function can exec a program if it
1463 thinks it knows what to do. Note that the name of the program
1464 appears twice in the arguments to %exec-failure, once as a file‐
1465 name and once as the first element of the argv array; in some
1466 cases the two will be identical, but in others the former will
1467 be a full pathname and the latter will just be the basename.
1468 Some versions of xs may provide a builtin version of this func‐
1469 tion to handle #!-style shell scripts if the kernel does not.
1470
1471 %exit-on-false cmd
1472 Runs the command, and exits if any command (except those execut‐
1473 ing as the tests of conditional statements) returns a non-zero
1474 status. (This function is used as an argument to %batch-loop
1475 and %interactive-loop when the shell is invoked with the -e
1476 option.)
1477
1478 %flatten separator list
1479 Concatenate the elements of list into one string, separated by
1480 the string separator.
1481
1482 %here fd word ... cmd
1483 Runs the command with the words passed as input on file descrip‐
1484 tor fd.
1485
1486 %home [user]
1487 Returns the home directory of the named user, or $home if there
1488 are no arguments.
1489
1490 %interactive-loop
1491 Prompts, parses commands from the current input source and
1492 passes the commands to the function %dispatch, which is usually
1493 a dynamically bound identifier. This function catches the
1494 exception eof which causes it to return. This function is
1495 invoked by the shell on startup and from the dot (.) commands,
1496 when the input source is interactive. (See also %batch-loop.)
1497
1498 %noeval-noprint cmd
1499 Do nothing. (Passed as the argument to %batch-loop and %inter‐
1500 active-loop when the -n option is used.)
1501
1502 %noeval-print cmd
1503 Print but don't run the command. (Passed as the argument to
1504 %batch-loop and %interactive-loop when the -x and -n options are
1505 used.)
1506
1507 %not cmd
1508 Runs the command and returns false if its exit status was true,
1509 otherwise returns true.
1510
1511 %one list
1512 If list is one element long, %one returns its value; otherwise
1513 it raises an exception. %one is used to ensure that redirection
1514 operations get passed exactly one filename.
1515
1516 %open fd file cmd
1517 Runs the command with file open for reading on file descriptor
1518 fd.
1519
1520 %open-append fd file cmd
1521 Runs the command with file open for reading and appending on
1522 file descriptor fd.
1523
1524 %open-create fd file cmd
1525 Runs the command with file open for reading and writing on file
1526 descriptor fd. If the file already exists, it is truncated.
1527
1528 %open-write fd file cmd
1529 Runs the command with file open for reading and writing on file
1530 descriptor fd.
1531
1532 %openfile mode fd file cmd
1533 Runs the command with file opened according to mode on file
1534 descriptor fd. The modes (r, w, a, r+, w+, and a+) have the
1535 same meanings in %openfile as they do in fopen(3). %openfile is
1536 invoked by the redirection hook functions: %append, %create,
1537 %open, %open-append, %open-create, and %open-write.
1538
1539 %or cmd ...
1540 Runs the commands in order, stopping after the first one that
1541 has a true return value. Returns the result of the last command
1542 run.
1543
1544 %parse prompt1 prompt2
1545 Reads input from the current input source, printing prompt1
1546 before reading anything and prompt2 before reading continued
1547 lines. Returns a code fragment suitable for execution. Raises
1548 the exception eof on end of input.
1549
1550 %pathsearch program
1551 Looks for an executable file named program in the directories
1552 listed in $path. If such a file is found, it is returned; if
1553 one is not found, an error exception is raised.
1554
1555 %pipe cmd [outfd infd cmd] ...
1556 Runs the commands, with the file descriptor outfd in the left-
1557 hand process connected by a pipe to the file descriptor infd in
1558 the right-hand process. If there are more than two commands, a
1559 multi-stage pipeline is created.
1560
1561 %prompt
1562 Called by %interactive-loop before every call to %parse. This
1563 function allows the user to provide any actions that he or she
1564 may wish to have executed before being prompted (e.g., updating
1565 the value of the prompt variable to contain all or part of the
1566 current working directory).
1567
1568 %readfrom var input cmd
1569 Runs cmd with the variable var locally bound to the name of a
1570 file which contains the output of running the command input.
1571
1572 %seq cmd ...
1573 Runs the commands, in order.
1574
1575 %whatis program ...
1576 For each named program, returns the pathname, primitive, lambda,
1577 or code fragment which would be run if the program appeared as
1578 the first word of a command.
1579
1580 %writeto var output cmd
1581 Runs cmd with the variable var locally bound to the name of a
1582 file which is used as the input for the command output.
1583
1584 Utility Functions
1585 These functions are useful for people customizing the shell, may be
1586 used by other builtin commands, and probably don't make much sense to
1587 replace, though that is always possible.
1588
1589 %apids Returns the process IDs of all background processes that the
1590 shell has not yet waited for.
1591
1592 %fsplit separator [args ...]
1593 Splits its arguments into separate strings at every occurrence
1594 of any of the characters in the string separator. Repeated
1595 instances of separator characters cause null strings to appear
1596 in the result. (This function is used by some builtin settor
1597 functions.)
1598
1599 %is-interactive
1600 Returns true if the current interpreter context is interactive;
1601 that is, if shell command input is currently coming from an
1602 interactive user. More precisely, this is true if the innermost
1603 enclosing read-eval-print loop is %interactive-loop rather than
1604 %batch-loop.
1605
1606 %newfd Returns a file descriptor that the shell thinks is not currently
1607 in use.
1608
1609 %run program argv0 args ...
1610 Run the named program, which is not searched for in $path, with
1611 the argument vector set to the remaining arguments. This
1612 builtin can be used to set argv[0] (by convention, the name of
1613 the program) to something other than file name.
1614
1615 %split separator [args ...]
1616 Splits its arguments into separate strings at every occurrence
1617 of any of the characters in the string separator. Repeated
1618 instances of separator characters are coalesced. Backquote sub‐
1619 stitution splits with the same rules.
1620
1621 %var var ...
1622 For each named variable, returns a string which, if interpreted
1623 by xs would assign to the variable its current value.
1624
1626 Primitives exist in xs so that, in the presence of spoofing and redefi‐
1627 nitions, there is a way to refer to built-in behaviors. This ability
1628 is necessary for the shell to be able to unambiguously refer to itself,
1629 but is also useful for users who have otherwise made their environment
1630 unnecessary but don't want to kill the current shell.
1631
1632 Primitives are referenced with the
1633
1634 $&name
1635
1636 notation. In this section, the ``$&'' prefixes will be omitted when
1637 primitive names are mentioned. Note that, by convention, primitive
1638 names follow C identifier names where xs variable and function names
1639 often contain ``%'' and ``-'' characters.
1640
1641 The following primitives directly implement the builtin functions with
1642 the same names:
1643
1644 access fork throw
1645 catch if umask
1646 echo newpgrp wait
1647 exec printf
1648 forever result
1649
1650 In addition, the primitive dot implements the ``.'' builtin function.
1651
1652 The cd primitive is used in the implementation of the cd builtin, but
1653 does not understand no arguments to imply $home. The vars and inter‐
1654 nals primitives are used by the implementation of the vars builtin.
1655
1656 The following primitives implement the hook functions of the same
1657 names, with ``%'' prefixes:
1658
1659 apids here run
1660 close home seq
1661 cmp newfd split
1662 count openfile var
1663 dup parse whatis
1664 flatten pipe
1665 fsplit read
1666
1667 The following primitives implement the similar named hook functions,
1668 with ``%'' prefixes and internal hyphens:
1669
1670 batchloop exitonfalse isinteractive
1671
1672 The background primitive is used to implement the %background hook
1673 function, but does not print the process ID of the background process
1674 or set $apid. The backquote primitive is used to implement the %back‐
1675 quote hook function, but returns the exit status of the child as the
1676 first value of its result instead of setting $bqstatus to it.
1677
1678 The following primitives implement the similarly named settor func‐
1679 tions:
1680
1681 sethistory setnoexport setsignals
1682
1683 The setmaxevaldepth primitive implements the settor function for the
1684 max-eval-depth variable, which is used to limit the depth of the inter‐
1685 preter's evaluation stack.
1686
1687 Some primitives are included in xs conditionally, based on compile-time
1688 configuration options. Those primitives, and the functions to which
1689 they are bound, are
1690
1691 execfailure %exec-failure
1692 limit limit
1693 readfrom %readfrom
1694 time time
1695 writeto %writeto
1696
1697 The primitive resetterminal is present if xs is compiled with support
1698 for the readline library. It is used in the implementation of settor
1699 functions of the TERM and TERMCAP variables to notify the line editing
1700 packages that the terminal configuration has changed.
1701
1702 Several primitives are not directly associated with other function.
1703 They are:
1704
1705 $&collect
1706 Invokes the garbage collector. The garbage collector in xs runs
1707 rather frequently; there should be no reason for a user to issue
1708 this command.
1709
1710 $&primitives
1711 Returns a list of the names of xs primitives.
1712
1713 $&random
1714 Returns a random integer.
1715
1716 $&version
1717 Returns the version string of xs.
1718
1720 -c Run the given command, placing the rest of the arguments to xs
1721 in $*.
1722
1723 -s Read commands from standard input; i.e., put the first argument
1724 to xs in $* rather than using it as the name of a file to
1725 source.
1726
1727 -i Force xs to be an interactive shell after loading $home/.xsin.
1728 Normally xs is only interactive if it is run with commands com‐
1729 ing from standard input and standard input is connected to a
1730 terminal.
1731
1732 -l Run $home/.xsrc on startup, i.e., be a login shell. -l is
1733 implied if the name the shell was run under (that is, argv[0])
1734 starts with a dash (-).
1735
1736 -e Exit if any command (except those executing as the tests of con‐
1737 ditional statements) returns a non-zero status.
1738
1739 -v Echo all input to standard error.
1740
1741 -x Print commands to standard error before executing them.
1742
1743 -n Turn off execution of commands. This can be used for checking
1744 the syntax of scripts. When combined with -x, xs prints the
1745 entered command based on the internal (parsed) representation.
1746
1747 -p Don't initialize functions from the environment. This is used
1748 to help make scripts that don't break unexpectedly when the
1749 environment contains functions that would override commands used
1750 in the script.
1751
1752 -o Don't open /dev/null on file descriptors 0, 1, and 2, if any of
1753 those descriptors are inherited closed.
1754
1755 -d Don't trap SIGQUIT or SIGTERM. This is used for debugging.
1756
1758 When built with the readline library, command and history editing is
1759 provided by the libary.
1760
1762 As with any other shell scripting language, process forking takes up
1763 the majority of time:
1764
1765 x = 0; while {!~ $x 4000} { x = `($x + 1) }
1766
1767 is several magnitudes faster than:
1768
1769 x = 0; while {test $x -ne 4000} { x = `($x + 1) }
1770
1771 Even though xs's arithmetic code is rather slow, in this case the cost
1772 of fork+exec far outweighs it.
1773
1774 Elaborate tricks involving stringifying closures and unstringying them
1775 later will probably not work. In general, trying to manipulate the
1776 scope of variables through similar techniques will probably not do what
1777 one expects.
1778
1780 $home/.xsrc, $home/.xsin, /dev/null
1781
1783 The interpreter should be properly tail recursive; that is, tail calls
1784 should not consume stack space.
1785
1786 Woe betide the environment string set by some other program to contain
1787 either the character control-a or the sequence control-b followed by
1788 control-a or control-b.
1789
1790 -x is not nearly as useful as it should be.
1791
1792 Too many creatures have fept in.
1793
1794 Please submit issues and pull requests at https://github.com/TieDyed‐
1795 Devil/XS.
1796
1798 history(1), readline(1), es(1), rc(1), sh(1), execve(2), getrlimit(2),
1799 fopen(3), getpwent(3), printf(3p)
1800
1801 Paul Haahr and Byron Rakitzis, Es — A shell with higher-order func‐
1802 tions, Proceedings of the Winter 1993 Usenix Conference, San Diego, CA.
1803
1804 Tom Duff, Rc — A Shell for Plan 9 and UNIX Systems, Unix Research Sys‐
1805 tem, 10th Edition, Volume 2. (Saunders College Publishing)
1806
1807
1808
1809 2017 - v1.1 XS(1)