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

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