Warning: Work in progress! Leave feedback on Zulip or Github if you'd like this doc to be updated.

Variable Scope in Shell and Oil

This is for advanced users. Casual users should can read the first two sections.

Also see Oil Keywords.

Table of Contents
Oil Design Goals
Dynamic Scope Example
What Most Users Need to Know
Three Keywords
When Dynamic Scope Is Off
More Constructs for Power Users
Three Semantics for Cell Lookup
scope_e.Dynamic
scope_e.LocalOrGlobal
scope_e.LocalOnly
Where Are These Semantics Used?
LocalOrGlobal For Reading Variables, and for setvar
DynamicLocalOnly (keyword setlocal)
Unchanged: Builtins That Take "Out Params" (keyword setref)
More Details
scope_e.GlobalOnly and setglobal
Other Assignment Constructs
Interactive Use
Related Links

Oil Design Goals

This doc is filled with details, so it will help to keep these goals in mind:

Dynamic Scope Example

TODO: Improve This Example

f() {
  out1='y'
  setvar out2 = 'y'
}

g() {
  local out1
  local out2

  f
}

g  # when it calls f, its variables can be modified

shopt --unset dynamic_scope
g  # now they can't be modified; they will be set globally

What Most Users Need to Know

Three Keywords

Don't use the old style of local, readonly, x=y.

This covers 95%+ of shell programming.

When Dynamic Scope Is Off

shopt --unset dynamic_scope

This option affects how nearly every shell assignment construct behaves. There are a lot of them!

This option is unset in bin/oil, but not bin/osh.

That's it!

More Constructs for Power Users

See Oil Keywords.

Read on if you want details.

Three Semantics for Cell Lookup

Cells are locations for variables.

Named after enums.

scope_e.Dynamic

What shell uses

scope_e.LocalOrGlobal

In Oil, it does one of three things:

  1. mutates an existing local
  2. mutates an existing global
  3. create a new global

In shell, it does these things:

  1. Mutate any variable of th e name up the stack.

scope_e.LocalOnly

The setlocal key always does the same thing. but all these other constructs switch between setvar and setlocal semantics, depending on shopt --unset dynamic_scope.

Where Are These Semantics Used?

LocalOrGlobal For Reading Variables, and for setvar

Constructs That Retrieve Cells:

The other ones deal with values. These deal with cells.

DynamicLocalOnly (keyword setlocal)

Shell:

These shell constructs mutate.

Unchanged: Builtins That Take "Out Params" (keyword setref)

These use setref semantics.

Idea: You can write functions with out params that also compose. TODO: Example.

More Details

scope_e.GlobalOnly and setglobal

This one is the easiest to explain, to we leave it for last.

Other Assignment Constructs

Interactive Use

Related Links


Generated on Sat Jan 23 00:06:31 PST 2021