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

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