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

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