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