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

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