OILS / doc / ref / chap-special-var.md View on Github | oils.pub

545 lines, 319 significant
1---
2title: Special Variables (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;
12Chapter **Special Variables**
13
14</div>
15
16This chapter describes special variables for OSH and YSH.
17
18<span class="in-progress">(in progress)</span>
19
20<div id="dense-toc">
21</div>
22
23## YSH Vars
24
25### ARGV
26
27ARGV is List of strings contaning an argument array. This is the YSH
28replacement for shell's `"$@"`.
29
30- At the top level, it contains the arguments passed to the shell.
31- Inside an **open** [proc][], it contains the arguments passed to the proc.
32
33For example:
34
35 proc p { # open proc, ARGV is swithout signature
36 echo @ARGV
37 }
38 p a b c # => a b c
39
40In contrast, inside a closed proc, `ARGV` is empty.
41
42 proc p () { # closed proc
43 echo @ARGV
44 }
45
46[proc]: chap-ysh-cmd.html#proc
47
48### ENV
49
50An `Obj` that's populated with environment variables. Example usage:
51
52 var x = ENV.PYTHONPATH
53 echo $[ENV.SSH_AUTH_SOCK]
54 setglobal ENV.PYTHONPATH = '.'
55
56It's initialized exactly **once** per process, in any of these situations:
57
581. At shell startup, if `shopt --set env_obj` is on. This is true when invoking
59 `bin/ysh`.
602. When running `bin/osh -o ysh:upgrade` or `ysh:all`.
613. When running `shopt --set ysh:upgrade` or `ysh:all`.
62
63Related: [ysh-shopt][], [osh-usage][]
64
65[ysh-shopt]: chap-builtin-cmd.html#ysh-shopt
66[osh-usage]: chap-front-end.html#osh-usage
67
68---
69
70When launching an external command, the shell creates a Unix `environ` from the
71`ENV` Obj. This means that mutating it affects all subsequent processes:
72
73 setglobal ENV.PYTHONPATH = '.'
74 ./foo.py
75 ./bar.py
76
77You can also limit the change to a single process, without `ENV`:
78
79 PYTHONPATH=. ./foo.py
80 ./bar.py # unaffected
81
82---
83
84YSH reads these ENV variables:
85
86- `PATH` - where to look for executables
87- `PS1` - how to print the prompt
88- TODO: `PS4` - how to show execution traces
89- `YSH_HISTFILE` (`HISTFILE` in OSH) - where to read/write command history
90- `HOME` - for tilde substitution ([tilde-sub])
91
92[tilde-sub]: chap-word-lang.html#tilde-sub
93
94### `__defaults__`
95
96The shell puts some default settings in this `Dict`. In certain situations, it
97consults `__defaults__` after consulting `ENV`. For example:
98
99- if `ENV.PATH` is not set, consult `__defaults__.PATH`
100- if `ENV.PS1` is not set, consult `__defaults__.PS1`
101
102<!-- TODO: consider renaming to DEF.PS1 ? -->
103
104### `__builtins__`
105
106An object that contains names visible in every module.
107
108If a name is not visible in the local scope, or module global scope, then it's
109looked up in `__builtins__`.
110
111### `__sh_function__`
112
113A Dict that reflects the shell functions defined in the Oils interpreter.
114
115 = keys(__sh_function__) # enumerate all shell functions
116
117 = get(__sh_function__, 'f') # get a value of type Proc
118
119 = __sh_function__ => get('f') # synonym for the above
120
121You can reflect on [doc comments][doc-comment] by calling the [docComment][]
122method on a value of type [Proc][].
123
124[doc-comment]: chap-front-end.html#doc-comment
125[docComment]: chap-type-method.html#docComment
126[Proc]: chap-type-method.html#Proc
127
128### `_this_dir`
129
130The directory the current script resides in. This knows about 3 situations:
131
132- The location of `oshrc` in an interactive shell
133- The location of the main script, e.g. in `osh myscript.sh`
134- The location of script loaded with the `source` builtin
135
136It's useful for "relative imports".
137
138## YSH Status
139
140### `_status`
141
142DEPRECATED: Use `_error.code` instead.
143
144### `_error`
145
146A `Dict` that's set by the `try` builtin.
147
148The integer `_error.code` is always present:
149
150 try {
151 ls /tmp
152 }
153 echo "status is $[_error.code]"
154
155Some errors also have a `message` field, like JSON/J8 encoding/decoding errors,
156and user errors from the [error][] builtin.
157
158 try {
159 echo $[toJson( /d+/ )] # invalid Eggex type
160 }
161 echo "failed: $[_error.message]" # => failed: Can't serialize ...
162
163[error]: chap-builtin-cmd.html#error
164
165
166### `_pipeline_status`
167
168After a pipeline of processes is executed, this array contains the exit code of
169each process.
170
171Each exit code is an [Int](chap-type-method.html#Int). Compare with
172[`PIPESTATUS`](#PIPESTATUS).
173
174### `_process_sub_status`
175
176The exit status of all the process subs in the last command.
177
178## YSH Tracing
179
180### SHX_indent
181
182### SHX_punct
183
184### SHX_pid_str
185
186## YSH Read
187
188### _reply
189
190Builtins that `read` set this variable:
191
192 read --all < foo.txt
193 = _reply # => 'contents of file'
194
195 json read < foo.json
196 = _reply # => (Dict) {}
197
198## Oils VM
199
200### `OILS_VERSION`
201
202The version of Oils that's being run, e.g. `0.23.0`.
203
204<!-- TODO: specify comparison algorithm. -->
205
206### `LIB_OSH`
207
208The string `///osh`, which you can use with the [source][] builtin.
209
210 source $LIB_OSH/two.sh
211
212[source]: chap-builtin-cmd.html#source
213
214### `LIB_YSH`
215
216The string `///ysh`, which you can use with the [source][] builtin.
217
218 source $LIB_YSH/yblocks.ysh
219
220[source]: chap-builtin-cmd.html#source
221
222### `OILS_GC_THRESHOLD`
223
224At a GC point, if there are more than this number of live objects, collect
225garbage.
226
227### `OILS_GC_ON_EXIT`
228
229Set `OILS_GC_ON_EXIT=1` to explicitly collect and `free()` before the process
230exits. By default, we let the OS clean up.
231
232Useful for ASAN testing.
233
234### `OILS_GC_STATS`
235
236When the shell process exists, print GC stats to stderr.
237
238### `OILS_GC_STATS_FD`
239
240When the shell process exists, print GC stats to this file descriptor.
241
242### `OILS_LOCALE_OK`
243
244Suppress the warning about `libc` locales that are not UTF-8.
245
246## libc locale
247
248### osh-locale
249
250At startup, reads these env vars and sets global vars in `libc`:
251
252- `LC_CTYPE`
253 - Affects how certain `libc` string functions handle bytes versus code
254 points. For example, what do `?` in globs and `.` in regexes mean?
255- `LC_COLLATE`
256 - Affects [glob][osh-glob] sort order.
257
258This is done with libc's `setlocale()` function.
259
260[osh-glob]: chap-word-lang.html#osh-glob
261
262### ysh-locale
263
264At startup, reads these env vars and sets global vars in `libc`:
265
266- `LC_CTYPE`
267
268This is done with libc's `setlocale()` function.
269
270[ysh-glob]: chap-word-lang.html#ysh-glob
271
272## Interactive
273
274### OILS_COMP_UI
275
276Set which completion UI to use. Defaults to `minimal`.
277
278- `minimal` - a UI that approximates the default behavior of GNU readline.
279- `nice` - a UI with a fancy pager and a prompt with horizontal scrolling instead of wrapping.
280
281This variable is currently only checked once during shell initialization.
282
283### HISTFILE
284
285Override the default OSH history location.
286
287### YSH_HISTFILE
288
289Override the default YSH history location.
290
291## Float
292
293### NAN
294
295The float value for "not a number".
296
297(The name is consistent with the C language.)
298
299### INFINITY
300
301The float value for "infinity". You can negate it to get "negative infinity".
302
303(The name is consistent with the C language.)
304
305## Module
306
307### `__provide__`
308
309A module is evaluated upon `use`. After evaluation, the names in the
310`__provide__` `List` are put in the resulting module `Obj` instance.
311
312<!--
313`__provide__` may also be a string, where 'p' stands for --procs, and 'f' stands for funcs.
314
315Or we could make it [1, 2] insetad
316-->
317
318## POSIX Special
319
320 $@ $* all arguments
321 $0 ... $9 ${10} each argument
322 $# the number of arguments
323 $? last exit status
324 $-
325 $$ PID of shell (does not change when shell forks)
326 $! ID of last job started, with & or bg
327
328Details on `$!`:
329
330- It's either
331 - the PID of a process
332 - the PID of the *last* part of the pipeline. (In contrast, the PGID of the
333 pipeline is the PID of the first part.)
334- The [`wait`](chap-builtin-cmd.html#wait) builtin knows how to find a
335 background pipeline job, given this ID.
336- It's set by:
337 - [`ampersand &`](chap-cmd-lang.html#ampersand)
338 - [`bg`](chap-builtin-cmd.html#bg)
339 - In particular, it's not set after Ctrl-Z, only after `bg`.
340
341## Shell Vars
342
343### IFS
344
345Used for word splitting. And the builtin `shSplit()` function.
346
347### LANG
348
349TODO: bash compat
350
351### GLOBIGNORE
352
353A colon-separated list of glob patterns that determines which filenames are
354ignored during pathname expansion (globbing).
355
356When `GLOBIGNORE` is set to a non-empty value:
357
358- Glob patterns automatically match dotfiles (files starting with `.`), similar
359 to the `dotglob` shell option
360- Files matching any pattern in `GLOBIGNORE` are excluded from glob results
361- The special files `.` and `..` are **always** filtered out, even if they
362 don't match any pattern
363
364Examples:
365
366 GLOBIGNORE='*.txt' # Ignore all .txt files
367 echo * # Shows all files except *.txt
368
369 GLOBIGNORE='*.o:*.h' # Ignore .o and .h files (colon-separated)
370 echo hello*
371
372 GLOBIGNORE='dist/*:node_modules/*' # Ignore directory contents
373 echo */*
374
375 GLOBIGNORE='.:..' # Match dotfiles, but filter . and ..
376 echo .* # Shows .env, .gitignore, etc. (not . or ..)
377
378Pattern syntax supports standard glob metacharacters:
379
380- `*` - matches any string
381- `?` - matches any single character
382- `[...]` - matches character classes, including `[[:alnum:]]`, `[[:space:]]`, etc.
383
384Note: Colons inside bracket expressions like `[[:alnum:]]` are treated as part
385of the pattern, not as separators.
386
387When `GLOBIGNORE` is unset or set to an empty string, glob expansion returns to
388its default behavior.
389
390## Shell Options
391
392### SHELLOPTS
393
394bash compat: serialized options for the `set` builtin.
395
396### BASHOPTS
397
398bash compat: serialized options for the `shopt` builtin.
399
400(Not implemented.)
401
402## Other Env
403
404### HOME
405
406The `$HOME` env var is read by the shell, for:
407
4081. `~` expansion
4092. `~` abbreviation in the UI (the dirs builtin, `\W` in `$PS1`).
410
411The shell does not set $HOME. According to POSIX, the program that invokes the
412login shell should set it, based on `/etc/passwd`.
413
414### PATH
415
416A colon-separated string that's used to find executables to run.
417
418In YSH, it's `ENV.PATH`.
419
420## Other Special
421
422### BASH_REMATCH
423
424Result of regex evaluation `[[ $x =~ $pat ]]`.
425
426### PIPESTATUS
427
428After a pipeline of processes is executed, this array contains the exit code of
429each process.
430
431Each exit code is a [Str](chap-type-method.html#Str). Compare with
432[`_pipeline_status`](#_pipeline_status).
433
434## Platform
435
436### HOSTNAME
437
438The name of the "host" or machine that Oils is running on, determined by
439`gethostname()`.
440
441### OSTYPE
442
443The operating system that Oils is running on, determined by `uname()`.
444
445Examples: `linux darwin ...`
446
447## Call Stack
448
449### BASH_SOURCE
450
451### FUNCNAME
452
453### BASH_LINENO
454
455## Tracing
456
457### LINENO
458
459## Process State
460
461### BASHPID
462
463TODO
464
465### PPID
466
467TODO
468
469### UID
470
471### EUID
472
473## Process Stack
474
475## Shell State
476
477## Completion
478
479### COMP_WORDS
480
481An array of words, split by : and = for compatibility with bash. New
482completion scripts should use COMP_ARGV instead.
483
484### COMP_CWORD
485
486Discouraged; for compatibility with bash.
487
488### COMP_LINE
489
490Discouraged; for compatibility with bash.
491
492### COMP_POINT
493
494Discouraged; for compatibility with bash.
495
496### COMP_WORDBREAKS
497
498Discouraged; for compatibility with bash.
499
500### COMPREPLY
501
502User-defined completion functions should Fill this array with candidates. It
503is cleared on every completion request.
504
505### COMP_ARGV
506
507An array of partial command arguments to complete. Preferred over COMP_WORDS.
508The compadjust builtin uses this variable.
509
510(An OSH extension to bash.)
511
512## cd
513
514### PWD
515
516### OLDPWD
517
518### CDPATH
519
520## getopts
521
522### OPTIND
523
524### OPTARG
525
526### OPTERR
527
528## read
529
530### REPLY
531
532OSH read sets this:
533
534 read < myfile
535
536## Functions
537
538### RANDOM
539
540bash compat
541
542### SECONDS
543
544bash compat
545