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

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