OILS / doc / ref / chap-builtin-cmd.md View on Github | oilshell.org

1460 lines, 926 significant
1---
2title: Builtin Commands (Oils Reference)
3all_docs_url: ..
4body_css_class: width40
5default_highlighter: oils-sh
6preserve_anchor_case: yes
7---
8
9<div class="doc-ref-header">
10
11[Oils Reference](index.html) &mdash; Chapter **Builtin Commands**
12
13</div>
14
15This chapter in the [Oils Reference](index.html) describes builtin commands for OSH and YSH.
16
17<span class="in-progress">(in progress)</span>
18
19<div id="dense-toc">
20</div>
21
22## Memory
23
24### cmd/append
25
26Append word arguments to a list:
27
28 var mylist = :| hello |
29
30 append *.py (mylist) # append all Python files
31
32 var myflags = []
33 append -- -c 'echo hi' (myflags) # -- to avoid ambiguity
34
35It's a shortcut for:
36
37 call myflags->append('-c')
38 call myflags->append('echo hi')
39
40Similar names: [append][]
41
42[append]: chap-index.html#append
43
44### pp
45
46The `pp` builtin pretty prints values and interpreter state.
47
48Pretty printing expressions is the most common:
49
50 $ var x = 42
51 $ pp (x + 5)
52 myfile.ysh:1: (Int) 47 # print value with code location
53
54You can pass an unevaluated expression:
55
56 $ pp [x + 5]
57 myfile.ysh:1: (Int) 47 # evaluate first
58
59The `value` command is a synonym for the interactive `=` operator:
60
61 $ pp value (x)
62 (Int) 42
63
64 $ = x
65 (Int) 42
66
67Print proc names and doc comments:
68
69 $ pp proc # subject to change
70
71You can also print low-level interpreter state. The trailing `_` indicates
72that the exact format may change:
73
74Examples:
75
76 $ var x = :| one two |
77
78 $ pp asdl_ (x) # dump the ASDL "guts"
79
80 $ pp test_ (x) # single-line stable format, for spec tests
81
82 # dump the ASDL representation of a "Cell", which is a location for a value
83 # (not the value itself)
84 $ pp cell_ x
85
86
87## Handle Errors
88
89### error
90
91The `error` builtin interrupts shell execution.
92
93If there's a surrounding `try` block, the `_error` register is set, and
94execution proceeds after the block.
95
96Otherwise, the shell exits with a non-zero status.
97
98Examples:
99
100 error 'Missing /tmp' # program fails with status 10
101
102 try {
103 error 'Another problem'
104 }
105 echo $[error.code] # => 10
106
107Override the default error code of `10` with a named argument:
108
109 error 'Missing /tmp' (code=99) # program fails with status 99
110
111Named arguments add arbitrary properties to the resulting `_error` register:
112
113 error 'Oops' (path='foo.json')
114
115See [YSH Error Handling](../ysh-error-handling.html) for more examples.
116
117### failed
118
119A shortcut for `(_error.code !== 0)`:
120
121 try {
122 ls /tmp
123 }
124 if failed {
125 echo 'ls failed'
126 }
127
128It saves you 7 punctuation characters: `( _ . !== )`
129
130See [YSH Error Handling](../ysh-error-handling.html) for more examples.
131
132### try
133
134Run a block of code, stopping at the first error. (This is implemented with
135`shopt --set errexit`)
136
137`try` sets the `_error` register to a dict, and always returns 0.
138
139 try {
140 ls /nonexistent
141 }
142 if (_error.code !== 0) {
143 echo 'ls failed'
144 }
145
146Handle expression errors:
147
148 try {
149 var x = 42 / 0
150 }
151
152And errors from compound commands:
153
154 try {
155 ls | wc -l
156 diff <(sort left.txt) <(sort right.txt)
157 }
158
159The case statement can be useful:
160
161 try {
162 grep PATTERN FILE.txt
163 }
164 case (_error.code) {
165 (0) { echo 'found' }
166 (1) { echo 'not found' }
167 (else) { echo "grep returned status $[_error.code]" }
168 }
169
170See [YSH Error Handling](../ysh-error-handling.html) for more examples.
171
172### boolstatus
173
174Runs a command, and requires the exit code to be 0 or 1.
175
176 if boolstatus egrep '[0-9]+' myfile { # e.g. aborts on status 2
177 echo 'found' # status 0 means found
178 } else {
179 echo 'not found' # status 1 means not found
180 }
181
182It's meant for external commands that "return" more than 2 values, like true /
183false / fail, rather than pass / fail.
184
185### assert
186
187Evaluates and expression, and fails if it is not truthy.
188
189 assert (false) # fails
190 assert [false] # also fails (the expression is evaluated)
191
192It's common to pass an unevaluated expression with `===`:
193
194 func f() { return (42) }
195
196 assert [43 === f()]
197
198In this special case, you get a nicer error message:
199
200> Expected: 43
201> Got: 42
202
203That is, the left-hand side should be the expected value, and the right-hand
204side should be the actual value.
205
206## Shell State
207
208### ysh-cd
209
210It takes a block:
211
212 cd / {
213 echo $PWD
214 }
215
216### ysh-shopt
217
218Sets shell options, e.g.
219
220 shopt --unset errexit
221 shopt --set errexit
222
223You can set or unset multiple options with the groups `strict:all`,
224`ysh:upgrade`, and `ysh:all`. Example:
225
226 shopt --set ysh:upgrade
227
228If a block is passed, then:
229
2301. the mutated options are pushed onto a stack
2312. the block is executed
2323. the options are restored to their original state (even if the block fails to
233 execute)
234
235Example:
236
237 shopt --unset errexit {
238 false
239 echo 'ok'
240 }
241
242Note that setting `ysh:upgrade` or `ysh:all` may initialize the [ENV][] dict.
243
244Related: [shopt](#shopt)
245
246[ENV]: chap-special-var.html#ENV
247
248### shvar
249
250Execute a block with a global variable set.
251
252 shvar IFS=/ {
253 echo "ifs is $IFS"
254 }
255 echo "ifs restored to $IFS"
256
257### ctx
258
259Execute a block with a shared "context" that can be updated using the `ctx`
260built-in.
261
262 var mydict = {}
263 ctx push (mydict) {
264 # = mydict => {}
265 ctx set (mykey='myval')
266 }
267 # = mydict => { mykey: 'myval' }
268
269The context can be modified with `ctx set (key=val)`, which updates or inserts
270the value at the given key.
271
272The context can also be updated with `ctx emit field (value)`.
273
274 ctx push (mydict) {
275 # = mydict => {}
276 ctx emit mylist (0)
277 # = mydict => { mylist: [0] }
278 ctx emit mylist (1)
279 }
280 # = mydict => { mylist: [0, 1] }
281
282Contexts can be nested, resulting in a stack of contexts.
283
284 ctx push (mydict1) {
285 ctx set (dict=1)
286 ctx push (mydict2) {
287 ctx set (dict=2)
288 }
289 }
290 # = mydict1 => { dict: 1 }
291 # = mydict2 => { dict: 2 }
292
293`ctx` is useful for creating DSLs, such as a mini-parseArgs.
294
295 proc parser (; place ; ; block_def) {
296 var p = {}
297 ctx push (p, block_def)
298 call place->setValue(p)
299 }
300
301 proc flag (short_name, long_name; type; help) {
302 ctx emit flag ({short_name, long_name, type, help})
303 }
304
305 proc arg (name) {
306 ctx emit arg ({name})
307 }
308
309 parser (&spec) {
310 flag -t --tsv (Bool, help='Output as TSV')
311 flag -r --recursive (Bool, help='Recurse into the given directory')
312 flag -N --count (Int, help='Process no more than N files')
313 arg path
314 }
315
316### push-registers
317
318Save global registers like $? on a stack. It's useful for preventing plugins
319from interfering with user code. Example:
320
321 status_42 # returns 42 and sets $?
322 push-registers { # push a new frame
323 status_43 # top of stack changed here
324 echo done
325 } # stack popped
326 echo $? # 42, read from new top-of-stack
327
328Current list of registers:
329
330 Regex data underlying BASH_REMATCH, _group(), _start(), _end()
331 $?
332 _error # set by the try builtin
333 PIPESTATUS # aka _pipeline_status
334 _process_sub_status
335
336
337## Modules
338
339### runproc
340
341Runs a named proc with the given arguments. It's often useful as the only top
342level statement in a "task file":
343
344 proc p {
345 echo hi
346 }
347 runproc @ARGV
348
349Like 'builtin' and 'command', it affects the lookup of the first word.
350
351### source-guard
352
353Registers a name in the global "module" dict. Returns 0 if it doesn't exist,
354or 1 if it does.
355
356Use it like this in executable files:
357
358 source-guard main || return 0
359
360And like this in libraries:
361
362 source-guard myfile.ysh || return 0
363
364### is-main
365
366The `is-main` builtin returns 1 (false) if the current file was executed with
367the `source` builtin.
368
369In the "main" file, including `-c` or `stdin` input, it returns 0 (true).
370
371Use it like this:
372
373 if is-main {
374 runproc @ARGV
375 }
376
377### use
378
379The `use` builtin evaluates a source file in a new `Frame`, and then creates an
380`Obj` that is a namespace.
381
382 use my-dir/mymodule.ysh
383
384 echo $[mymodule.my_integer] # the module Obj has attributes
385 mymodule my-proc # the module Obj is invokable
386
387The evaluation of such files is cached, so it won't be re-evaluated if `use` is
388called again.
389
390To import a specific name, use the `--pick` flag:
391
392 use my-dir/mymodule.ysh --pick my-proc other-proc
393
394 my-proc 1 2
395 other-proc 3 4
396
397Note: the `--pick` flag must come *after* the module, so this isn't valid:
398
399 use --pick my-proc mymodule.sh # INVALID
400
401<!--
402# TODO:
403
404use mod.ysh --all-provided # relies on __provide__ or provide builtin
405use mod.ysh --all-for-testing
406-->
407
408---
409
410The `--extern` flag means that `use` does nothing. These commands can be used
411by tools to analyze names.
412
413 use --extern grep sed awk
414
415---
416
417Notes:
418
419- To get a reference to `module-with-hyphens`, you may need to use
420 `getVar('module-with-hyphens')`.
421 - TODO: consider backtick syntax as well
422- `use` must be used at the top level, not within a function.
423 - This behavior is unlike Python.
424
425Warnings:
426
427- `use` **copies** the module bindings into a new `Obj`. This means that if
428 you rebind `mymodule.my_integer`, it will **not** be visible to code in the
429 module.
430 - This behavior is unlike Python.
431- `use` allows "circular imports". That is `A.ysh` can `use B.ysh`, and vice
432 versa.
433 - To eliminate confusion over uninitialized names, use **only** `const`,
434 `func`, and `proc` at the top level of `my-module.ysh`. Don't run
435 commands, use `setvar`, etc.
436
437## I/O
438
439### ysh-read
440
441YSH adds long flags to shell's `read`:
442
443 read --all # whole file including trailing \n, fills $_reply
444 read --all (&x) # fills $x
445
446 read --num-bytes 3 # read N bytes, fills _reply
447 read --num-bytes 3 (&x) # fills $x
448
449 read --raw-line # unbuffered read of line, omitting trailing \n
450 read --raw-line (&x) # fills $x
451
452 read --raw-line --with-eol # include the trailing \n
453
454And a convenience:
455
456 read -0 # read until NUL, synonym for read -r -d ''
457
458You may want to use `fromJson8()` or `fromJson()` after reading a line.
459
460<!--
461
462TODO:
463
464- read --netstr
465- fromJ8Line() is different than from Json8! It's like @()
466
467-->
468
469<!--
470
471Problem with read --json -- there's also https://jsonlines.org, which allows
472
473 {"my": "line"}
474
475That can be done with
476
477 while read --line {
478 var record = fromJson(_reply)
479 }
480
481This is distinct from:
482
483 while read --line --j8 {
484 echo $_reply
485 }
486
487This allows unquoted. Maybe it should be read --j8-line
488
489What about write? These would be the same:
490
491 write --json -- $s
492 write --j8 -- $s
493
494 write -- $[toJson(s)]
495 write -- $[toJson8(s)]
496
497 write --json -- @strs
498 write --j8 -- @strs
499
500 write -- @[toJson(s) for s in strs]
501 write -- @[toJson8(s) for s in strs]
502
503It's an argument for getting rid --json and --j8? I already implemented them,
504but it makes the API smaller.
505
506I guess the main thing would be to AVOID quoting sometimes?
507
508 $ write --j8 -- unquoted
509 unquoted
510
511 $ write --j8 -- $'\'' '"'
512 "'"
513 "\""
514
515I think this could be the shell style?
516
517 $ write --shell-str -- foo bar baz
518
519Or it could be
520
521 $ write -- @[toShellString(s) for s in strs]
522
523I want this to be "J8 Lines", but it can be done in pure YSH. It's not built
524into the interpreter.
525
526 foo/bar
527 "hi"
528b'hi'
529u'hi'
530
531But what about
532
533 Fool's Gold
534a'hi' # This feels like an error?
535a"hi" # what about this?
536
537Technically we CAN read those as literal strings
538-->
539
540### ysh-echo
541
542Print arguments to stdout, separated by a space.
543
544 ysh$ echo hi there
545 hi there
546
547The [simple_echo][] option means that flags aren't accepted, and `--` is not
548accepted.
549
550 ysh$ echo -n
551 -n
552
553See the [YSH FAQ][echo-en] for details.
554
555[simple_echo]: chap-option.html#ysh:all
556[echo-en]: ../ysh-faq.html#how-do-i-write-the-equivalent-of-echo-e-or-echo-n
557
558### ysh-test
559
560The YSH [test](#test) builtin supports these long flags:
561
562 --dir same as -d
563 --exists same as -e
564 --file same as -f
565 --symlink same as -L
566
567 --true Is the argument equal to the string "true"?
568 --false Is the argument equal to the string "false"?
569
570The `--true` and `--false` flags can be used to combine commands and
571expressions:
572
573 if test --file a && test --true $[bool(mydict)] {
574 echo ok
575 }
576
577This works because the boolean `true` *stringifies* to `"true"`, and likewise
578with `false`.
579
580That is, `$[true] === "true"` and `$[false] === "false"`.
581
582### write
583
584write fixes problems with shell's `echo` builtin.
585
586The default separator is a newline, and the default terminator is a
587newline.
588
589Examples:
590
591 write -- ale bean # write two lines
592
593 write -n -- ale bean # synonym for --end '', like echo -n
594 write --sep '' --end '' -- a b # write 2 bytes
595 write --sep $'\t' --end $'\n' -- a b # TSV line
596
597You may want to use `toJson8()` or `toJson()` before writing:
598
599 write -- $[toJson8(mystr)]
600 write -- $[toJson(mystr)]
601
602
603<!--
604 write --json -- ale bean # JSON encode, guarantees two lines
605 write --j8 -- ale bean # J8 encode, guarantees two lines
606-->
607
608
609### fork
610
611Run a command, but don't wait for it to finish.
612
613 fork { sleep 1 }
614 wait -n
615
616In YSH, use `fork` rather than shell's `&` ([ampersand][]).
617
618[ampersand]: chap-cmd-lang.html#ampersand
619
620### forkwait
621
622The preferred alternative to shell's `()`. Prefer `cd` with a block if possible.
623
624 forkwait {
625 not_mutated=zzz
626 }
627 echo $not_mutated
628
629### fopen
630
631Runs a block passed to it. It's designed so redirects have a **prefix**
632syntax:
633
634 fopen >out.txt {
635 echo 1
636 echo 2
637 }
638
639Rather than shell style:
640
641 { echo 1
642 echo 2
643 } >out.txt
644
645When a block is long, the former is more readable.
646
647## Hay Config
648
649### hay
650
651### haynode
652
653
654## Data Formats
655
656### json
657
658Write JSON:
659
660 var d = {name: 'bob', age: 42}
661 json write (d) # default indentation of 2
662 json write (d, space=0) # no indentation
663
664Read JSON:
665
666 echo hi | json read # fills $_reply by default
667
668Or use an explicit place:
669
670 var x = ''
671 json read (&x) < myfile.txt
672
673Related: [err-json-encode][] and [err-json-decode][]
674
675[err-json-encode]: chap-errors.html#err-json-encode
676[err-json-decode]: chap-errors.html#err-json-decode
677
678### json8
679
680Like `json`, but on the encoding side:
681
682- Falls back to `b'\yff'` instead of lossy Unicode replacement char
683
684On decoding side:
685
686- Understands `b'' u''` strings
687
688Related: [err-json8-encode]() and [err-json8-decode]()
689
690[err-json8-encode]: chap-errors.html#err-json8-encode
691[err-json8-decode]: chap-errors.html#err-json8-decode
692
693## Testing
694
695TODO: describe
696
697## External Lang
698
699TODO: when
700
701
702## I/O
703
704These builtins take input and output. They're often used with redirects.
705
706### read
707
708 read FLAG* VAR*
709
710Read a line from stdin, split it into tokens with the `$IFS` algorithm,
711and assign the tokens to the given variables. When no VARs are given,
712assign to `$REPLY`.
713
714Note: When writing ySH, prefer the extensions documented in
715[ysh-read](#ysh-read). The `read` builtin is confusing because `-r` needs to
716be explicitly enabled.
717
718Flags:
719
720 -a ARRAY assign the tokens to elements of this array
721 -d CHAR use DELIM as delimiter, instead of newline
722 -n NUM read up to NUM characters, respecting delimiters
723 -p STR print the string PROMPT before reading input
724 -r raw mode: don't let backslashes escape characters
725 -s silent: do not echo input coming from a terminal
726 -t NUM time out and fail after TIME seconds
727 -t 0 returns whether any input is available
728 -u FD read from file descriptor FD instead of 0 (stdin)
729
730 <!-- -N NUM read up to NUM characters, ignoring delimiters -->
731 <!-- -e use readline to obtain the line
732 -i STR use STR as the initial text for readline -->
733
734### echo
735
736 echo FLAG* ARG*
737
738Prints ARGs to stdout, separated by a space, and terminated by a newline.
739
740Flags:
741
742 -e enable interpretation of backslash escapes
743 -n omit the trailing newline
744<!-- -E -->
745
746See [char-escapes](chap-mini-lang.html#char-escapes).
747
748### printf
749
750 printf FLAG* FMT ARG*
751
752Formats values and prints them. The FMT string contain three types of objects:
753
7541. Literal Characters
7552. Character escapes like `\t`. See [char-escapes](chap-mini-lang.html#char-escapes).
7563. Percent codes like `%s` that specify how to format each each ARG.
757
758If not enough ARGS are passed, the empty string is used. If too many are
759passed, the FMT string will be "recycled".
760
761Flags:
762
763 -v VAR Write output in variable VAR instead of standard output.
764
765Format specifiers:
766
767 %% Prints a single "%".
768 %b Interprets backslash escapes while printing.
769 %q Prints the argument escaping the characters needed to make it reusable
770 as shell input.
771 %d Print as signed decimal number.
772 %i Same as %d.
773 %o Print as unsigned octal number.
774 %u Print as unsigned decimal number.
775 %x Print as unsigned hexadecimal number with lower-case hex-digits (a-f).
776 %X Same as %x, but with upper-case hex-digits (A-F).
777 %f Print as floating point number.
778 %e Print as a double number, in "±e" format (lower-case e).
779 %E Same as %e, but with an upper-case E.
780 %g Interprets the argument as double, but prints it like %f or %e.
781 %G Same as %g, but print it like %E.
782 %c Print as a single char, only the first character is printed.
783 %s Print as string
784 %n The number of characters printed so far is stored in the variable named
785 in the argument.
786 %a Interprets the argument as double, and prints it like a C99 hexadecimal
787 floating-point literal.
788 %A Same as %a, but print it like %E.
789 %(FORMAT)T Prints date and time, according to FORMAT as a format string
790 for strftime(3). The argument is the number of seconds since
791 epoch. It can also be -1 (current time, also the default value
792 if there is no argument) or -2 (shell startup time).
793
794### readarray
795
796Alias for `mapfile`.
797
798### mapfile
799
800 mapfile FLAG* ARRAY?
801
802Reads lines from stdin into the variable named ARRAY (default
803`${MAPFILE[@]}`).
804
805Flags:
806
807 -t Remove the trailing newline from every line
808<!--
809 -d CHAR use CHAR as delimiter, instead of the default newline
810 -n NUM copy up to NUM lines
811 -O NUM begins copying lines at the NUM element of the array
812 -s NUM discard the first NUM lines
813 -u FD read from FD file descriptor instead of the standard input
814 -C CMD run CMD every NUM lines specified in -c
815 -c NUM every NUM lines, the CMD command in C will be run
816-->
817
818## Run Code
819
820These builtins accept shell code and run it.
821
822### source
823
824 source SCRIPT ARG*
825
826Execute SCRIPT with the given ARGs, in the context of the current shell. That is,
827existing variables will be modified.
828
829---
830
831Oils extension: If the SCRIPT starts with `///`, we look for scripts embedded in
832the `oils-for-unix` binary. Example:
833
834 source ///osh/two.sh # load embedded script
835
836 : ${LIB_OSH=fallback/dir}
837 source $LIB_OSH/two.sh # same thing
838
839The [LIB_OSH][] form is useful for writing a script that works under both bash
840and OSH.
841
842- Related: the [cat-em][] tool prints embedded scripts.
843
844[LIB_OSH]: chap-special-var.html#LIB_OSH
845[cat-em]: chap-front-end.html#cat-em
846
847
848### eval
849
850 eval ARG+
851
852Creates a string by joining ARGs with a space, then runs it as a shell command.
853
854Example:
855
856 # Create the string echo "hello $name" and run it.
857 a='echo'
858 b='"hello $name"'
859 eval $a $b
860
861Tips:
862
863- Using `eval` can confuse code and user-supplied data, leading to [security
864issues][].
865- Prefer passing single string ARG to `eval`.
866
867[security issues]: https://mywiki.wooledge.org/BashFAQ/048
868
869### trap
870
871 trap FLAG* CMD SIGNAL*
872
873Registers the shell string CMD to be run after the SIGNALs are received. If
874the CMD is empty, then the signal is ignored.
875
876Flags:
877
878 -l Lists all signals and their signal number
879 -p Prints a list of the installed signal handlers
880
881Tip:
882
883Prefer passing the name of a shell function to `trap`.
884
885## Set Options
886
887The `set` and `shopt` builtins set global shell options. YSH code should use
888the more natural `shopt`.
889
890### set
891
892 set FLAG* ARG*
893
894Sets global shell options. Short style:
895
896 set -e
897
898Long style:
899
900 set -o errexit
901
902Set the arguments array:
903
904 set -- 1 2 3
905
906### shopt
907
908 shopt FLAG* OPTION* BLOCK?
909
910Sets global shell options.
911
912Flags:
913
914 -s --set Turn the named options on
915 -u --unset Turn the named options off
916 -p Print option values, and 1 if any option is unset
917 -o Use older set of options, normally controlled by 'set -o'
918 -q Return 0 if the option is true, else 1
919
920This command is compatible with `shopt` in bash. See [ysh-shopt](#ysh-shopt) for
921details on YSH enhancements.
922
923## Working Dir
924
925These 5 builtins deal with the working directory of the shell.
926
927### cd
928
929 cd FLAG* DIR
930
931Changes the working directory of the current shell process to DIR.
932
933If DIR isn't specified, change to `$HOME`. If DIR is `-`, change to `$OLDPWD`
934(a variable that the sets to the previous working directory.)
935
936Flags:
937
938 -L Follow symbolic links, i.e. change to the TARGET of the symlink.
939 (default).
940 -P Don't follow symbolic links.
941
942### pwd
943
944 pwd FLAG*
945
946Prints the current working directory.
947
948Flags:
949
950 -L Follow symbolic links if present (default)
951 -P Don't follow symbolic links. Print the link instead of the target.
952
953### pushd
954
955<!--pushd FLAGS DIR-->
956 pushd DIR
957<!--pushd +/-NUM-->
958
959Add DIR to the directory stack, then change the working directory to DIR.
960Typically used with `popd` and `dirs`.
961
962<!--FLAGS:
963 -n Don't change the working directory, just manipulate the stack
964NUM:
965 Rotates the stack the number of places specified. Eg, given the stack
966 '/foo /bar /baz', where '/foo' is the top of the stack, pushd +1 will move
967 it to the bottom, '/bar /baz /foo'-->
968
969### popd
970
971 popd
972
973Removes a directory from the directory stack, and changes the working directory
974to it. Typically used with `pushd` and `dirs`.
975
976### dirs
977
978 dirs FLAG*
979
980Shows the contents of the directory stack. Typically used with `pushd` and
981`popd`.
982
983Flags:
984
985 -c Clear the dir stack.
986 -l Show the dir stack, but with the real path instead of ~.
987 -p Show the dir stack, but formatted as one line per entry.
988 -v Like -p, but numbering each line.
989
990## Completion
991
992These builtins implement our bash-compatible autocompletion system.
993
994### complete
995
996Registers completion policies for different commands.
997
998### compgen
999
1000Generates completion candidates inside a user-defined completion function.
1001
1002It can also be used in scripts, i.e. outside a completion function.
1003
1004### compopt
1005
1006Changes completion options inside a user-defined completion function.
1007
1008### compadjust
1009
1010Adjusts `COMP_ARGV` according to specified delimiters, and optionally set
1011variables cur, prev, words (an array), and cword. May also set 'split'.
1012
1013This is an OSH extension that makes it easier to run the bash-completion
1014project.
1015
1016### compexport
1017
1018Complete an entire shell command string. For example,
1019
1020 compexport -c 'echo $H'
1021
1022will complete variables like `$HOME`. And
1023
1024 compexport -c 'ha'
1025
1026will complete builtins like `hay`, as well as external commands.
1027
1028
1029## Shell Process
1030
1031These builtins mutate the state of the shell process.
1032
1033### exec
1034
1035 exec BIN_PATH ARG*
1036
1037Replaces the running shell with the binary specified, which is passed ARGs.
1038BIN_PATH must exist on the file system; i.e. it can't be a shell builtin or
1039function.
1040
1041### umask
1042
1043 umask MODE?
1044
1045Sets the bit mask that determines the permissions for new files and
1046directories. The mask is subtracted from 666 for files and 777 for
1047directories.
1048
1049Oils currently supports writing masks in octal.
1050
1051If no MODE, show the current mask.
1052
1053### ulimit
1054
1055 ulimit --all
1056 ulimit -a
1057 ulimit FLAGS* -RESOURCE_FLAG VALUE?
1058
1059 ulimit FLAGS* VALUE? # discouraged
1060
1061Show and modify process resource limits.
1062
1063Flags:
1064
1065 -S for soft limit
1066 -H for hard limit
1067
1068 -c -d -f ... # ulimit --all shows all resource flags
1069
1070Show a table of resources:
1071
1072 ulimit --all
1073 ulimit -a
1074
1075For example, the table shows that `-n` is the flag that controls the number
1076file descriptors, the soft and hard limit for `-n`, and the multiplication
1077"factor" for the integer VALUE you pass.
1078
1079---
1080
1081Here are examples of using resource flags.
1082
1083Get the soft limit for the number of file descriptors:
1084
1085 ulimit -S -n
1086 ulimit -n # same thing
1087
1088Get the hard limit:
1089
1090 ulimit -H -n
1091
1092Set the soft or hard limit:
1093
1094 ulimit -S -n 100
1095 ulimit -H -n 100
1096
1097Set both limits:
1098
1099 ulimit -n 100
1100
1101A special case that's discouraged: with no resource flag, `-f` is assumed:
1102
1103 ulimit # equivalent to ulimit -f
1104 ulimit 100 # equivalent to ulimit -f 100
1105
1106### times
1107
1108 times
1109
1110Shows the user and system time used by the shell and its child processes.
1111
1112## Child Process
1113
1114### jobs
1115
1116 jobs
1117
1118Shows all jobs running in the shell and their status.
1119
1120### wait
1121
1122 wait FLAG* ARG
1123
1124Wait for processes to exit.
1125
1126If the ARG is a PID, wait only for that job, and return its status.
1127
1128If there's no ARG, wait for all child processes.
1129
1130<!--
1131The ARG can be a PID (tracked by the kernel), or a job number (tracked by the
1132shell). Specify jobs with the syntax `%jobnumber`.
1133-->
1134
1135Flags:
1136
1137 -n Wait for the next process to exit, rather than a specific process.
1138
1139Wait can be interrupted by a signal, in which case the exit code indicates the
1140signal number.
1141
1142### fg
1143
1144 fg JOB?
1145
1146Returns a job running in the background to the foreground. If no JOB is
1147specified, use the latest job.
1148
1149<!--<h4 id="bg">bg</h4>
1150
1151The bg builtin resumes suspend job, while keeping it in the background.
1152
1153bg JOB?
1154
1155JOB:
1156 Job ID to be resumed in the background. If none is specified, the latest job
1157 is chosen. -->
1158
1159### kill
1160
1161Unimplemented.
1162
1163<!-- Note: 'kill' accepts job control syntax -->
1164
1165## External
1166
1167### test
1168
1169 test OP ARG
1170 test ARG OP ARG
1171 [ OP ARG ] # [ is an alias for test that requires closing ]
1172 [ ARG OP ARG ]
1173
1174Evaluates a conditional expression and returns 0 (true) or 1 (false).
1175
1176Note that `[` is the name of a builtin, not an operator in the language. Use
1177`test` to avoid this confusion.
1178
1179String expressions:
1180
1181 -n STR True if STR is not empty.
1182 'test STR' is usually equivalent, but discouraged.
1183 -z STR True if STR is empty.
1184 STR1 = STR2 True if the strings are equal.
1185 STR1 != STR2 True if the strings are not equal.
1186 STR1 < STR2 True if STR1 sorts before STR2 lexicographically.
1187 STR1 > STR2 True if STR1 sorts after STR2 lexicographically.
1188 Note: < and > should be quoted like \< and \>
1189
1190File expressions:
1191
1192 -a FILE Synonym for -e.
1193 -b FILE True if FILE is a block special file.
1194 -c FILE True if FILE is a character special file.
1195 -d FILE True if FILE is a directory.
1196 -e FILE True if FILE exists.
1197 -f FILE True if FILE is a regular file.
1198 -g FILE True if FILE has the sgid bit set.
1199 -G FILE True if current user's group is also FILE's group.
1200 -h FILE True if FILE is a symbolic link.
1201 -L FILE True if FILE is a symbolic link.
1202 -k FILE True if FILE has the sticky bit set.
1203 -O FILE True if current user is the file owner.
1204 -p FILE True if FILE is a named pipe (FIFO).
1205 -r FILE True if FILE is readable.
1206 -s FILE True if FILE has size bigger than 0.
1207 -S FILE True if FILE is a socket file.
1208 -t FD True if file descriptor FD is open and refers to a terminal.
1209 -u FILE True if FILE has suid bit set.
1210 -w FILE True if FILE is writable.
1211 -x FILE True if FILE is executable.
1212 FILE1 -nt FILE2 True if FILE1 is newer than FILE2 (mtime).
1213 FILE1 -ot FILE2 True if FILE1 is older than FILE2 (mtime).
1214 FILE1 -ef FILE2 True if FILE1 is a hard link to FILE2.
1215<!-- -N FILE True if FILE was modified since last read (mtime newer than atime).-->
1216
1217Arithmetic expressions coerce arguments to integers, then compare:
1218
1219 INT1 -eq INT2 True if they're equal.
1220 INT1 -ne INT2 True if they're not equal.
1221 INT1 -lt INT2 True if INT1 is less than INT2.
1222 INT1 -le INT2 True if INT1 is less or equal than INT2.
1223 INT1 -gt INT2 True if INT1 is greater than INT2.
1224 INT1 -ge INT2 True if INT1 is greater or equal than INT2.
1225
1226Other expressions:
1227
1228 -o OPTION True if the shell option OPTION is set.
1229 -v VAR True if the variable VAR is set.
1230
1231The test builtin also supports POSIX conditionals like -a, -o, !, and ( ), but
1232these are discouraged.
1233
1234<!-- -R VAR True if the variable VAR has been set and is a nameref variable. -->
1235
1236---
1237
1238See [ysh-test](#ysh-test) for log flags like `--file` and `--true`.
1239
1240### getopts
1241
1242 getopts SPEC VAR ARG*
1243
1244A single iteration of flag parsing. The SPEC is a sequence of flag characters,
1245with a trailing `:` to indicate that the flag takes an argument:
1246
1247 ab # accept -a and -b
1248 xy:z # accept -x, -y arg, and -z
1249
1250The input is `"$@"` by default, unless ARGs are passed.
1251
1252On each iteration, the flag character is stored in VAR. If the flag has an
1253argument, it's stored in `$OPTARG`. When an error occurs, VAR is set to `?`
1254and `$OPTARG` is unset.
1255
1256Returns 0 if a flag is parsed, or 1 on end of input or another error.
1257
1258Example:
1259
1260 while getopts "ab:" flag; do
1261 case $flag in
1262 a) flag_a=1 ;;
1263 b) flag_b=$OPTARG" ;;
1264 '?') echo 'Invalid Syntax'; break ;;
1265 esac
1266 done
1267
1268Notes:
1269- `$OPTIND` is initialized to 1 every time a shell starts, and is used to
1270 maintain state between invocations of `getopts`.
1271- The characters `:` and `?` can't be flags.
1272
1273
1274## Conditional
1275
1276### cmd/true
1277
1278Do nothing and return status 0.
1279
1280 if true; then
1281 echo hello
1282 fi
1283
1284### cmd/false
1285
1286Do nothing and return status 1.
1287
1288 if false; then
1289 echo 'not reached'
1290 else
1291 echo hello
1292 fi
1293
1294<h3 id="colon" class="osh-topic">colon :</h3>
1295
1296Like `true`: do nothing and return status 0.
1297
1298## Introspection
1299
1300<h3 id="help" class="osh-topic ysh-topic" oils-embed="1">
1301 help
1302</h3>
1303
1304<!-- pre-formatted for help builtin -->
1305
1306```
1307Usage: help TOPIC?
1308
1309Examples:
1310
1311 help # this help
1312 help echo # help on the 'echo' builtin
1313 help command-sub # help on command sub $(date)
1314
1315 help oils-usage # identical to oils-for-unix --help
1316 help osh-usage # osh --help
1317 help ysh-usage # ysh --help
1318```
1319
1320### hash
1321
1322 hash
1323
1324Display information about remembered commands.
1325
1326 hash FLAG* CMD+
1327
1328Determine the locations of commands using `$PATH`, and remember them.
1329
1330Flag:
1331
1332 -r Discard all remembered locations.
1333<!-- -d Discard the remembered location of each NAME.
1334 -l Display output in a format reusable as input.
1335 -p PATH Inhibit path search, PATH is used as location for NAME.
1336 -t Print the full path of one or more NAME.-->
1337
1338### cmd/type
1339
1340 type FLAG* NAME+
1341
1342Print the type of each NAME, if it were the first word of a command. Is it a
1343shell keyword, builtin command, shell function, alias, or executable file on
1344$PATH?
1345
1346Flags:
1347
1348 -a Show all possible candidates, not just the first one
1349 -f Don't search for shell functions
1350 -P Only search for executable files
1351 -t Print a single word: alias, builtin, file, function, or keyword
1352
1353Similar names: [type][]
1354
1355[type]: chap-index.html#type
1356
1357<!-- TODO:
1358- procs are counted as shell functions, should be their own thing
1359- Hay nodes ('hay define x') also live in the first word namespace, and should
1360 be recognized
1361-->
1362
1363Modeled after the [bash `type`
1364builtin](https://www.gnu.org/software/bash/manual/bash.html#index-type).
1365
1366## Word Lookup
1367
1368### command
1369
1370 command FLAG* CMD ARG*
1371
1372Look up CMD as a shell builtin or executable file, and execute it with the
1373given ARGs. That is, the lookup ignores shell functions named CMD.
1374
1375Flags:
1376
1377 -v Instead of executing CMD, print a description of it.
1378 Similar to the 'type' builtin.
1379<!-- -p Use a default value for PATH that is guaranteed to find all of the
1380 standard utilities.
1381 -V Print a more verbose description of CMD.-->
1382
1383### builtin
1384
1385 builtin CMD ARG*
1386
1387Look up CMD as a shell builtin, and execute it with the given ARGs. That is,
1388the lookup ignores shell functions and executables named CMD.
1389
1390## Interactive
1391
1392### alias
1393
1394 alias NAME=CODE
1395
1396Make NAME a shortcut for executing CODE, e.g. `alias hi='echo hello'`.
1397
1398 alias NAME
1399
1400Show the value of this alias.
1401
1402 alias
1403
1404Show a list of all aliases.
1405
1406Tips:
1407
1408Prefer shell functions like:
1409
1410 ls() {
1411 command ls --color "$@"
1412 }
1413
1414to aliases like:
1415
1416 alias ls='ls --color'
1417
1418Functions are less likely to cause parsing problems.
1419
1420- Quoting like `\ls` or `'ls'` disables alias expansion
1421- To remove an existing alias, use [unalias](chap-builtin-cmd.html#unalias).
1422
1423### unalias
1424
1425 unalias NAME
1426
1427Remove the alias NAME.
1428
1429<!--Flag:
1430
1431 -a Removes all existing aliases.-->
1432
1433### history
1434
1435 history FLAG*
1436
1437Display and manipulate the shell's history entries.
1438
1439 history NUM
1440
1441Show the last NUM history entries.
1442
1443Flags:
1444
1445 -c Clears the history.
1446 -d POS Deletes the history entry at position POS.
1447<!-- -a
1448 -n
1449 -r
1450 -w
1451 -p
1452 -s -->
1453
1454
1455## Unsupported
1456
1457### enable
1458
1459Bash has this, but OSH won't implement it.
1460