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

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