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

547 lines, 320 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
155See [ysh-exit-codes][] for info on the `_error.code` field.
156
157Some errors also have a `message` field, like JSON/J8 encoding/decoding errors,
158and user errors from the [error][] builtin.
159
160 try {
161 echo $[toJson( /d+/ )] # invalid Eggex type
162 }
163 echo "failed: $[_error.message]" # => failed: Can't serialize ...
164
165[ysh-exit-codes]: chap-front-end.html#ysh-exit-codes
166[error]: chap-builtin-cmd.html#error
167
168
169### `_pipeline_status`
170
171After a pipeline of processes is executed, this array contains the exit code of
172each process.
173
174Each exit code is an [Int](chap-type-method.html#Int). Compare with
175[`PIPESTATUS`](#PIPESTATUS).
176
177### `_process_sub_status`
178
179The exit status of all the process subs in the last command.
180
181## YSH Tracing
182
183### SHX_indent
184
185### SHX_punct
186
187### SHX_pid_str
188
189## YSH Read
190
191### _reply
192
193Builtins that `read` set this variable:
194
195 read --all < foo.txt
196 = _reply # => 'contents of file'
197
198 json read < foo.json
199 = _reply # => (Dict) {}
200
201## Oils VM
202
203### `OILS_VERSION`
204
205The version of Oils that's being run, e.g. `0.23.0`.
206
207<!-- TODO: specify comparison algorithm. -->
208
209### `LIB_OSH`
210
211The string `///osh`, which you can use with the [source][] builtin.
212
213 source $LIB_OSH/two.sh
214
215[source]: chap-builtin-cmd.html#source
216
217### `LIB_YSH`
218
219The string `///ysh`, which you can use with the [source][] builtin.
220
221 source $LIB_YSH/yblocks.ysh
222
223[source]: chap-builtin-cmd.html#source
224
225### `OILS_GC_THRESHOLD`
226
227At a GC point, if there are more than this number of live objects, collect
228garbage.
229
230### `OILS_GC_ON_EXIT`
231
232Set `OILS_GC_ON_EXIT=1` to explicitly collect and `free()` before the process
233exits. By default, we let the OS clean up.
234
235Useful for ASAN testing.
236
237### `OILS_GC_STATS`
238
239When the shell process exists, print GC stats to stderr.
240
241### `OILS_GC_STATS_FD`
242
243When the shell process exists, print GC stats to this file descriptor.
244
245### `OILS_LOCALE_OK`
246
247Suppress the warning about `libc` locales that are not UTF-8.
248
249## libc locale
250
251### osh-locale
252
253At startup, reads these env vars and sets global vars in `libc`:
254
255- `LC_CTYPE`
256 - Affects how certain `libc` string functions handle bytes versus code
257 points. For example, what do `?` in globs and `.` in regexes mean?
258- `LC_COLLATE`
259 - Affects [glob][osh-glob] sort order.
260
261This is done with libc's `setlocale()` function.
262
263[osh-glob]: chap-word-lang.html#osh-glob
264
265### ysh-locale
266
267At startup, reads these env vars and sets global vars in `libc`:
268
269- `LC_CTYPE`
270
271This is done with libc's `setlocale()` function.
272
273[ysh-glob]: chap-word-lang.html#ysh-glob
274
275## Interactive
276
277### OILS_COMP_UI
278
279Set which completion UI to use. Defaults to `minimal`.
280
281- `minimal` - a UI that approximates the default behavior of GNU readline.
282- `nice` - a UI with a fancy pager and a prompt with horizontal scrolling instead of wrapping.
283
284This variable is currently only checked once during shell initialization.
285
286### HISTFILE
287
288Override the default OSH history location.
289
290### YSH_HISTFILE
291
292Override the default YSH history location.
293
294## Float
295
296### NAN
297
298The float value for "not a number".
299
300(The name is consistent with the C language.)
301
302### INFINITY
303
304The float value for "infinity". You can negate it to get "negative infinity".
305
306(The name is consistent with the C language.)
307
308## Module
309
310### `__provide__`
311
312A module is evaluated upon `use`. After evaluation, the names in the
313`__provide__` `List` are put in the resulting module `Obj` instance.
314
315<!--
316`__provide__` may also be a string, where 'p' stands for --procs, and 'f' stands for funcs.
317
318Or we could make it [1, 2] insetad
319-->
320
321## POSIX Special
322
323 $@ $* all arguments
324 $0 ... $9 ${10} each argument
325 $# the number of arguments
326 $? last exit status
327 $-
328 $$ PID of shell (does not change when shell forks)
329 $! ID of last job started, with & or bg
330
331Details on `$!`:
332
333- It's either
334 - the PID of a process
335 - the PID of the *last* part of the pipeline. (In contrast, the PGID of the
336 pipeline is the PID of the first part.)
337- The [`wait`](chap-builtin-cmd.html#wait) builtin knows how to find a
338 background pipeline job, given this ID.
339- It's set by:
340 - [`ampersand &`](chap-cmd-lang.html#ampersand)
341 - [`bg`](chap-builtin-cmd.html#bg)
342 - In particular, it's not set after Ctrl-Z, only after `bg`.
343
344## Shell Vars
345
346### IFS
347
348Used for word splitting. And the builtin `shSplit()` function.
349
350### LANG
351
352TODO: bash compat
353
354### GLOBIGNORE
355
356A colon-separated list of glob patterns that determines which filenames are
357ignored during pathname expansion (globbing).
358
359When `GLOBIGNORE` is set to a non-empty value:
360
361- Glob patterns automatically match dotfiles (files starting with `.`), similar
362 to the `dotglob` shell option
363- Files matching any pattern in `GLOBIGNORE` are excluded from glob results
364- The special files `.` and `..` are **always** filtered out, even if they
365 don't match any pattern
366
367Examples:
368
369 GLOBIGNORE='*.txt' # Ignore all .txt files
370 echo * # Shows all files except *.txt
371
372 GLOBIGNORE='*.o:*.h' # Ignore .o and .h files (colon-separated)
373 echo hello*
374
375 GLOBIGNORE='dist/*:node_modules/*' # Ignore directory contents
376 echo */*
377
378 GLOBIGNORE='.:..' # Match dotfiles, but filter . and ..
379 echo .* # Shows .env, .gitignore, etc. (not . or ..)
380
381The patterns use standard glob syntax (see [glob-pat][]). Note that colons
382inside bracket expressions like `[[:alnum:]]` are treated as part of the
383pattern, not as separators.
384
385When `GLOBIGNORE` is unset or set to an empty string, glob expansion returns to
386its default behavior.
387
388This is a bash-compatible feature.
389
390[glob-pat]: chap-mini-lang.html#glob-pat
391
392## Shell Options
393
394### SHELLOPTS
395
396bash compat: serialized options for the `set` builtin.
397
398### BASHOPTS
399
400bash compat: serialized options for the `shopt` builtin.
401
402(Not implemented.)
403
404## Other Env
405
406### HOME
407
408The `$HOME` env var is read by the shell, for:
409
4101. `~` expansion
4112. `~` abbreviation in the UI (the dirs builtin, `\W` in `$PS1`).
412
413The shell does not set $HOME. According to POSIX, the program that invokes the
414login shell should set it, based on `/etc/passwd`.
415
416### PATH
417
418A colon-separated string that's used to find executables to run.
419
420In YSH, it's `ENV.PATH`.
421
422## Other Special
423
424### BASH_REMATCH
425
426Result of regex evaluation `[[ $x =~ $pat ]]`.
427
428### PIPESTATUS
429
430After a pipeline of processes is executed, this array contains the exit code of
431each process.
432
433Each exit code is a [Str](chap-type-method.html#Str). Compare with
434[`_pipeline_status`](#_pipeline_status).
435
436## Platform
437
438### HOSTNAME
439
440The name of the "host" or machine that Oils is running on, determined by
441`gethostname()`.
442
443### OSTYPE
444
445The operating system that Oils is running on, determined by `uname()`.
446
447Examples: `linux darwin ...`
448
449## Call Stack
450
451### BASH_SOURCE
452
453### FUNCNAME
454
455### BASH_LINENO
456
457## Tracing
458
459### LINENO
460
461## Process State
462
463### BASHPID
464
465TODO
466
467### PPID
468
469TODO
470
471### UID
472
473### EUID
474
475## Process Stack
476
477## Shell State
478
479## Completion
480
481### COMP_WORDS
482
483An array of words, split by : and = for compatibility with bash. New
484completion scripts should use COMP_ARGV instead.
485
486### COMP_CWORD
487
488Discouraged; for compatibility with bash.
489
490### COMP_LINE
491
492Discouraged; for compatibility with bash.
493
494### COMP_POINT
495
496Discouraged; for compatibility with bash.
497
498### COMP_WORDBREAKS
499
500Discouraged; for compatibility with bash.
501
502### COMPREPLY
503
504User-defined completion functions should Fill this array with candidates. It
505is cleared on every completion request.
506
507### COMP_ARGV
508
509An array of partial command arguments to complete. Preferred over COMP_WORDS.
510The compadjust builtin uses this variable.
511
512(An OSH extension to bash.)
513
514## cd
515
516### PWD
517
518### OLDPWD
519
520### CDPATH
521
522## getopts
523
524### OPTIND
525
526### OPTARG
527
528### OPTERR
529
530## read
531
532### REPLY
533
534OSH read sets this:
535
536 read < myfile
537
538## Functions
539
540### RANDOM
541
542bash compat
543
544### SECONDS
545
546bash compat
547