interp

package
v0.0.0-...-79e800d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 34 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package interp is the interpreter of hail: the state of a shell, and the code that runs the tree of package syntax.

The package ports the interpreter of brush-core, as docs/PORT.md maps it. Each file names the file of brush that it follows. hail runs on goroutines and not on the async tasks of brush, so the port takes the behavior and the messages of brush, and not its structure. Where brush and bash differ, the package follows bash 5.3, whose answers are the golden files of the YAML cases.

The state of a shell

A Shell holds the variables, the functions, the options, the positional parameters, $?, the working directory, the umask, the table of file descriptors and the vfs.Namespace of its files. The directory and the umask are fields. The shell never calls os.Chdir, os.Setenv or syscall.Umask, and never calls dup2 on the descriptors of hail (D7).

Reading a program

Shell.Run reads one complete command, runs it, and then reads the next one, as bash does, through syntax.Reader (W28). It reads its input one byte at a time, so a child that reads the same input finds the rest of the script. . and eval, the action of a trap and the REPL read the same way. Each command takes the options of the shell at the time that it is read. With shopt expand_aliases on, they include the aliases, which the reader expands while it reads (W24). So a definition takes effect from the next command that the shell reads. brush expands an alias when a simple command runs, and hail does not.

Descriptors

The table of descriptors maps a number to an open file. A redirection changes the table and nothing else. Two descriptors that a duplication made share one open file, which closes when the last descriptor that refers to it goes away. Only a child gets real descriptors: the table gives each one as an *os.File in proc.Attr.Files. An open file that is not an *os.File, such as the body of a here-document, goes to the child through a pipe and a goroutine that copies the data.

Subshells

A subshell runs on a copy of the state (D6): the variables, the functions, the options and the parameters are copied, and the copy of the table shares the open files of its parent. Each stage of a pipeline of more than one command runs in a subshell on a goroutine of its own, joined to the next stage by a pipe of the system, so that a child gets a real descriptor. WebAssembly has no such pipe, and uses one in memory. A subshell in parentheses runs on the goroutine of its caller, which waits for it anyway. Every child starts through package proc.

A command substitution runs in a subshell on the goroutine of its caller too, and a goroutine reads its output from a pipe (subst.go). A list that ends with &, a process substitution and a coprocess each run as a job: a subshell on a goroutine of its own, with a made-up process ID as its $! (job.go, procsubst.go). A made-up process ID is above every process ID that a system gives, so kill never reaches a real process with one. A signal that kill sends to a job ends the job, or goes to the program of a job of one simple command. wait waits for the jobs of the shell.

bash starts a process for each subshell, so a script that starts subshells without end stops when the system refuses a process. hail counts its subshells instead. It refuses a subshell past a depth of 256, or past 4096 subshells on goroutines at once, with the error of bash for a process that the system refused.

A child whose umask or limits differ from those of hail starts through a copy of hail, which sets them and then runs the child in its own process (D6, proc.RunStarter). Config.Self names that copy.

Exit, return, break and continue

A function of the executor returns an error value to change the flow of a script. exit returns an *exitError, return a *returnError, and break and continue a *loopError. Each one rises through its callers to the construct that it ends: a loop, a function or a sourced file, or a subshell or the shell. A subshell turns each one into its status, so exit in a subshell ends only the subshell. A *discardError abandons the complete command that runs, as bash does after an assignment to a readonly variable. In an interactive shell, outside a subshell, it abandons only the complete command of the text of ., eval, fc or bind -x that runs, and that text goes on, as parse_and_execute of bash does. No panic is used, and none crosses a goroutine.

Variables and arrays

A variable is a scalar, an indexed array or an associative array, with the attributes of declare. An indexed array keeps its indices sorted, so it can be sparse. An associative array keeps its keys in the buckets of a hash table as bash does, so that ${!a[@]} lists them in the order of bash. Each assignment applies the attributes of its variable: declare -i evaluates the value as arithmetic, and -l, -u and -c change its case. The shell keeps FUNCNAME, BASH_SOURCE, BASH_LINENO and PIPESTATUS up to date as arrays, from its call stack and its pipelines.

The declaration builtins declare, typeset, local, export and readonly get the assignments of arrays in their arguments as they were written, and expand them once they know the kind of each variable. So the keys of declare -A a=([k]=v) are text, and not arithmetic.

Builtins

The builtins live in this package, one file for each builtin or small family, named builtin_*.go after it, with the file of brush-builtins that it follows in its header. A builtin reads and changes the variables, the options, the functions, the descriptors and the call stack of the shell, which are unexported. A package of their own needs all of that exported, so they stay beside the state that they change, and the API of the package stays small. builtins.go holds the table of builtins.

In POSIX mode, a special builtin comes before a function, the assignments before it stay, and its usage and assignment errors end a shell that is not interactive, as in bash.

Traps

trap.go runs the traps EXIT, ERR, DEBUG and RETURN at the points that bash runs them. Each process of the shell has a queue of signals (signals.go): the shell at the top, and each subshell, which runs in a goroutine with a process ID of its own. kill puts a signal in the queue of its process, and Shell.HandleSignals puts each signal that another process sends to hail in the queue of the shell at the top. A shell takes its signals between two commands and while it waits, and runs the trap, ignores the signal or ends, as bash does. While the line editor of an interactive shell waits for a key, Shell.AtPrompt acts on the signals that bash acts on while readline waits, and prints the notices of set -b (atprompt.go).

Jobs

job.go, jobctl.go and builtin_jobs.go hold the jobs and job control. A job of & runs in a subshell on a goroutine. When the shell is hail itself, the job also gets a keeper, a copy of hail whose process ID is the $! of the job, so that another program sees the job and signals it (proc.Keeper). With set -m, a program of the foreground leads a process group of its own and gets the terminal, a job of & runs in the process group of its keeper, and a pipeline or a subshell of the foreground gets a keeper too, which leads its group. Shell.SetTerminal takes the terminal for an interactive shell.

Windows

windows.go holds the rules that the shell follows on Windows (W12). The shell names a path as Git Bash does, as in /c/x, and msys.go converts the arguments and the environment of a program of Windows as Git Bash does (D36). PATH and CDPATH are lists split by ":", and Path in the environment becomes PATH. A command is found with the extensions of PATHEXT. A file can run when its extension is in PATHEXT, or when it starts with "#!" or "MZ", as Cygwin decides, so test -x decides the same way. A script with a #! line runs through the program that the line names, found in PATH by its last name. The shell drops the CR of each CRLF of the text that it reads, and a command substitution drops the CRs at its end, as Git for Windows does. A process substitution that is a word gives a temporary file (D12), and /dev/null is the device NUL. Ctrl-C reaches the shell through os/signal, kill reaches a program through proc.Kill, and the shell has no job control: no keeper, no process group and no stop.

What is left out

An expansion that package expand does not give yet ends the shell with a message. A program cannot see or signal the process ID of a subshell, a pipeline stage or a process substitution, which hail makes up. Windows has no job control: fg, bg, Ctrl-Z and the stop of a job need a stop, which Windows does not have.

Key bindings

bind works on a model of the keymaps of readline, which is what it prints, with or without a terminal (bind.go). An interactive shell on a terminal gets a KeyBinder from package repl, and each change to the model goes to it too, so that the keys that the editor runs stay in step with what bind shows (keybinder.go). set -o vi and set -o emacs set the editing mode of the model, and a key that switches the mode in the editor sets the options, as in bash. RunKeyCommand runs a shell command of bind -x on the line, the cursor, the mark and the numeric argument of the editor, and CompleteAs completes a word as a file, a command, a variable, a user, a host or a pattern, for the keys of bash that do so whatever the word is.

Index

Constants

View Source
const BashVersion = "5.3.0(1)-release"

BashVersion is the value of $BASH_VERSION: the release of bash that hail follows, in the form that bash gives it (D9, D11).

Variables

View Source
var (
	// ErrUnknownFunction is a function that the editor does not have.
	ErrUnknownFunction = errors.New("unknown function name")
	// ErrUnknownKeymap is a keymap that the editor does not have.
	ErrUnknownKeymap = errors.New("invalid keymap name")
	// ErrUnknownVariable is a variable that the editor does not have.
	ErrUnknownVariable = errors.New("unknown variable name")
	// ErrInvalidSequence is a key sequence that the editor cannot read.
	ErrInvalidSequence = errors.New("invalid key sequence")
	// ErrInvalidValue is a value that a variable cannot take.
	ErrInvalidValue = errors.New("invalid value")
)

The faults of a KeyBinder.

View Source
var (
	// ErrLineInterrupted is the error of ReadCommandLine when the user
	// gave the line up with Ctrl-C.
	ErrLineInterrupted = errors.New("the line was interrupted")
	// ErrEndAtPrompt is the error of ReadCommandLine when a trap that ran
	// while the shell waited for the line ran exit. Finish then gives the
	// status.
	ErrEndAtPrompt = errors.New("the shell ended at the prompt")
)

The errors of ReadCommandLine.

Functions

func ErrorText

func ErrorText(err error) string

ErrorText returns the text that the C library gives for the error err, as bash prints it, such as "No such file or directory".

func IsBuiltin

func IsBuiltin(name string) bool

IsBuiltin reports whether name is a builtin of hail.

func IsOption

func IsOption(name string) bool

IsOption reports whether name is an option of set -o, so that the command line can refuse a name as bash does, before the shell exists.

func IsShopt

func IsShopt(name string) bool

IsShopt reports whether name is an option of shopt.

func IsTerminal

func IsTerminal(f *os.File) bool

IsTerminal reports whether f is a terminal, as isatty does.

func ListOptions

func ListOptions(shopt, commands bool, on func(name string) bool) string

ListOptions returns every option of set -o, or of shopt with shopt, with the state that on gives it. Without commands, each line holds the name and on or off, as set -o and shopt print them. With commands, each line is a command that sets the option again, as set +o and shopt -p print them. bash lists the options so for a lone -o, +o, -O or +O on its command line.

func MachType

func MachType() string

MachType returns the type of the machine, as $MACHTYPE gives it, such as x86_64-pc-linux-gnu.

func OptionDefault

func OptionDefault(name string, shopt bool) bool

OptionDefault reports whether the option name of set -o, or of shopt with shopt, is on when a shell starts, before its command line and its startup files change it.

func ShellVersion

func ShellVersion() string

ShellVersion returns the line that bash's display-shell-version prints, on the key Ctrl-X Ctrl-V: the release of bash that hail follows and the type of the machine, as MACHTYPE gives it.

Types

type Completion

type Completion struct {
	// Text replaces Line[Start:Point] of the request.
	Text string
	// Display is what a list of the completions shows. An empty Display
	// shows Text.
	Display string
	// Suffix goes after Text when it is the only completion, such as a
	// space after a word or "/" after a directory.
	Suffix string
}

Completion is one way to complete a word.

type CompletionKind

type CompletionKind int

CompletionKind says what the word at the cursor is.

const (
	// CompleteArgument is a word after the name of a command.
	CompleteArgument CompletionKind = iota
	// CompleteCommand is the name of a command, at the start of a simple
	// command.
	CompleteCommand
	// CompleteVariable is the name of a variable, after $ or ${.
	CompleteVariable
	// CompleteFile is the target of a redirection, such as the word after >.
	CompleteFile
	// CompleteUser is the name of a user, as complete-username of bash
	// completes it.
	CompleteUser
	// CompleteHost is the name of a host, as complete-hostname of bash
	// completes it.
	CompleteHost
	// CompleteGlob is a pattern, which the names of the files that it
	// matches complete, as glob-expand-word of bash completes it.
	CompleteGlob
)

The kinds of words to complete.

type CompletionRequest

type CompletionRequest struct {
	// Line is the text of the simple command that holds the cursor, as
	// COMP_LINE gives it. It can be empty, when the cursor starts a command.
	Line string
	// Point is the cursor in Line, as COMP_POINT gives it.
	Point int
	// Start is where the word to complete starts in Line. Line[Start:Point]
	// is the text to complete. For CompleteVariable it starts after the $ or
	// the ${.
	Start int
	// Kind says what the word is.
	Kind CompletionKind
}

CompletionRequest is the word to complete, and the simple command around it, as the line editor found them.

type Config

type Config struct {
	// Name is $0. It is also the name at the start of each error message,
	// as "bash" is in "bash: line 1: x: command not found".
	Name string
	// ShellName is the name that the shell started under, the first word
	// of its command line, which \s of a prompt gives. It stays the same
	// when Name is a script or the name that -c gives. An empty ShellName
	// is Name.
	ShellName string
	// Args are the positional parameters, from $1 on.
	Args []string
	// Env is the environment, as "name=value" strings. Each one becomes an
	// exported variable.
	Env []string
	// Dir is the working directory. It must be absolute. The shell keeps it
	// as a field, and never calls os.Chdir (D7).
	Dir string
	// Stdin, Stdout and Stderr are descriptors 0, 1 and 2. A nil one is
	// closed. An *os.File goes to a child as it is. The shell does not
	// close them.
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// Files are more descriptors of the shell, by number, such as the
	// descriptors that hail got from its parent. The shell owns them, and
	// closes each one when no descriptor of the shell refers to it.
	Files map[int]*InheritedFile
	// Namespace gives the files of the shell. A nil Namespace is vfs.OS().
	Namespace vfs.Namespace
	// Umask is the umask of the shell, which it applies to each file that
	// it creates (D7). It is also the umask of the process of hail, which
	// a child gets when the shell has the same umask.
	Umask fs.FileMode
	// Path is $BASH, the path of the hail binary.
	Path string
	// Self is the path of the hail binary that starts a child that needs a
	// umask or a limit of its own, as a starter (D6). Its main function
	// calls proc.RunStarter first. With an empty Self, such a child gets
	// the umask and the limits of hail.
	Self string
	// Version is $HAIL_VERSION, the version of hail.
	Version string
	// Pid is $$. A zero Pid is the process ID of hail.
	Pid int
	// CommandString is true when the program comes from -c. It puts "-c"
	// in the messages of syntax errors, as bash does.
	CommandString bool
	// ExecutionString is the program of -c, which BASH_EXECUTION_STRING
	// holds when CommandString is true.
	ExecutionString string
	// Script is true when the program is a script file, named by Name.
	// The script is then the frame "main" at the bottom of the call stack,
	// as in FUNCNAME and BASH_SOURCE.
	Script bool
	// LogoutFile is the file that a login shell runs when exit, logout or
	// the end of the input at a prompt ends it, as bash runs
	// ~/.bash_logout. A "~/" at its start stands for $HOME. An empty
	// LogoutFile runs no file.
	LogoutFile string
	// Restricted is true when the shell starts restricted, by -r or under
	// the name rbash (D39). It takes no function from the environment, and
	// shopt restricted_shell is on. Shell.Restrict turns the restrictions
	// on, which a caller does after the startup files, as bash does.
	Restricted bool
	// BashHelp is true when help and --help of a builtin give the texts of
	// GNU bash, in a build with the tag gnubash that holds them (D38). Any
	// other shell gives the short texts of hail.
	BashHelp bool
}

Config is what a new shell starts with.

type InheritedFile

type InheritedFile struct {
	// File is the open file.
	File *os.File
	// Read and Write give the access of the file.
	Read, Write bool
}

InheritedFile is a descriptor that the shell gets from its caller.

type KeyBinder

type KeyBinder interface {
	// Bind binds seq in keymap to the function name, or to a macro when
	// name is in double quotes.
	Bind(keymap, seq, name string) error
	// Unbind takes away what seq in keymap runs.
	Unbind(keymap, seq string) error
	// BindShellCommand binds seq in keymap to a shell command, as bind -x
	// does. The editor runs it with Shell.RunKeyCommand.
	BindShellCommand(keymap, seq, command string) error
	// SetVariable sets a variable of readline, as "set name value" does in
	// an inputrc file.
	SetVariable(name, value string) error
	// Variables returns every variable of readline with its value now.
	Variables() map[string]string
}

KeyBinder is the line editor of an interactive shell, as bind, set -o vi and the key bindings of config.yaml change it. Package repl gives one for rline. A key sequence and the text of a macro are written as an inputrc file writes them between double quotes, such as \C-a. A keymap is emacs, vi-move or vi-insert.

An error wraps ErrUnknownFunction, ErrUnknownKeymap, ErrUnknownVariable, ErrInvalidSequence or ErrInvalidValue, and the shell prints it as bash prints the same fault.

type KeyLine

type KeyLine struct {
	// Text is the line, and Point the cursor in it.
	Text  string
	Point int
	// Mark is the mark, as set-mark and the kill commands set it.
	Mark int
	// Count is the numeric argument of the key, and CountGiven is true
	// when the user typed one.
	Count      int
	CountGiven bool
}

KeyLine is the line of the editor, as a shell command of bind -x sees it and changes it. Point and Mark are offsets in bytes.

type Shell

type Shell struct {
	// contains filtered or unexported fields
}

Shell is the state of a shell, and runs its commands.

A subshell runs on a copy of the state, made by subshell (D6). The copy holds the variables, the functions, the options, the positional parameters, the directory and the table of file descriptors.

func New

func New(cfg Config) *Shell

New returns a shell for the configuration.

func (*Shell) AddHistory

func (s *Shell) AddHistory(text string)

AddHistory adds the text of one command that the user typed to the history, as bash does after it reads the command. The text can hold more than one line. It applies set -o history, HISTCONTROL, HISTIGNORE, HISTSIZE and shopt cmdhist and lithist.

func (*Shell) Assign

func (s *Shell) Assign(name, value string) error

Assign sets the variable name to value, as name=value does, with the attributes of the variable. It implements expand.Env.

func (*Shell) AssignElement

func (s *Shell) AssignElement(name, key, value string) error

AssignElement sets the element of the array name at key to value. key is a decimal index for an indexed array. It implements expand.Env.

func (*Shell) AtEndOfInput

func (s *Shell) AtEndOfInput() bool

AtEndOfInput tells the shell that the input ended, as Ctrl-D on an empty line ends it. It reports whether the shell must end. With set -o ignoreeof, the shell refuses IGNOREEOF ends in a row, and says how to leave. A value of IGNOREEOF that is not all digits counts as 10, as in bash. Otherwise the shell writes "exit", as bash does.

func (*Shell) AtPrompt

func (s *Shell) AtPrompt(w io.Writer) bool

AtPrompt runs what waits for the shell at the top while the line editor waits for a key, as bash runs it while readline waits. With set -b, it writes to w the notices of the jobs that changed. It then acts on the signals in the queue of the shell that bash acts on at the prompt: it runs the trap, ignores the signal, or ends the shell. The other signals wait in the queue for the next command, unless a trap runs: the traps that wait run after its command, as bash runs every trap that waits. It reports whether the shell must end, because a trap ran exit. Finish then gives the status.

func (*Shell) BeforePrompt

func (s *Shell) BeforePrompt() bool

BeforePrompt runs what bash runs before it shows PS1: the commands of PROMPT_COMMAND, one for each element when it is an array. $? and $_ stay as they were, as in bash. It reports whether the shell must end, because a command of PROMPT_COMMAND ran exit. Finish then gives the status.

func (*Shell) BreakWord

func (s *Shell) BreakWord(req CompletionRequest) CompletionRequest

BreakWord moves the start of the word of req past the last character of COMP_WORDBREAKS in it that no quote holds, as readline does with rl_completer_word_break_characters, so that the text after the = of KUBECONFIG=$HOME/Down or of --file=Down completes. The text after the = of an assignment in the place of a command completes as the name of a file, as in bash. The line editor calls it before it takes the start of the word that a completion replaces, and Complete calls it again, which changes nothing.

func (*Shell) Complete

func (s *Shell) Complete(req CompletionRequest) (list []Completion, keepOrder bool)

Complete returns the completions of the word that req names, as bash completes it when the user presses Tab: by the specification of complete for the command, or else by the kind of the word.

keepOrder is true when the specification has the option nosort, as complete -o nosort and compopt -o nosort give it. The line editor then shows the completions in the order of list, and does not sort them.

A function of complete -F that ends the shell, with exit, ends only the completion here, because the line editor has no way to end the shell.

func (*Shell) CompleteAs

func (s *Shell) CompleteAs(req CompletionRequest) []Completion

CompleteAs returns the completions of the word that req names as req.Kind says, whatever the word is, as complete-filename, complete-command and their kin of bash complete it. It runs no specification of complete. A word to complete as a variable can start with $ or ${, a word to complete as a user with ~, and a word to complete as a host with @, and each completion keeps that start. CompleteArgument completes a file name, as CompleteFile does.

func (*Shell) DumpStrings

func (s *Shell) DumpStrings(po bool, name string)

DumpStrings makes the shell print each string of the form $"..." of its program as it reads it, as bash -D does: in double quotes, or with po in the form of a .po file of gettext, whose comments name the input name and a line. bash names -c for the program of -c, the name of a script, or its own name for standard input. The caller also turns noexec on, as bash does, so that the shell runs nothing.

func (*Shell) EchoesInput

func (s *Shell) EchoesInput() bool

EchoesInput reports whether the shell writes each line that it reads at its prompt to its standard error, as bash does through readline when readline reads a file that is not a terminal. On a terminal, the terminal shows what the user types, and with --noediting or set +o emacs bash reads its lines without readline and writes nothing.

func (*Shell) EditAndExecute

func (s *Shell) EditAndExecute(text string, vi bool) bool

EditAndExecute runs an editor on text, the line that the user typed, and then runs what the editor leaves, as edit-and-execute-command of bash does on Ctrl-X Ctrl-E. text goes to the history as it is, and fc edits it with $VISUAL, or else $EDITOR, or else emacs. With vi, as for the key v of vi mode, the last choice is vi. It reports whether the shell must end.

func (*Shell) Element

func (s *Shell) Element(name, key string) (string, error)

Element returns the element of the array name at key, for arithmetic. An index that counts back past the start of the array prints an error and gives "", as in bash. Under set -u, as in bash, a variable that is not set is an error that names the variable, and an element that is missing from a variable that is set is "". It implements arith.Env.

func (*Shell) ExpandHistory

func (s *Shell) ExpandHistory(text string) (expanded string, run bool)

ExpandHistory expands the history references of text, such as !!, as bash does before it runs a line that the user typed, when set -o histexpand is on. It expands each line of text by itself. When a line changes, it prints the expanded text on standard error, as bash does. run is false when the shell must not run the result: after an error, which it prints, and after the modifier :p, which prints the result instead. After :p, expanded holds the text that goes into the history.

func (*Shell) ExpandIndex

func (s *Shell) ExpandIndex(index string) (string, error)

ExpandIndex expands the index of an element of an indexed array in arithmetic, as bash 5.3 does: as in double quotes, with the double quotes removed, so that a["$i"] is a[1] when i is 1. The text of ((...)), $((...)) and the other arithmetic quoted its subscripts when it expanded (see expand.ArithText), so that this expansion gives the value of the first one, as in bash. With shopt array_expand_once on, the index of an expression of let, which was a word, does not expand again. It implements arith.IndexExpander.

func (*Shell) ExpandKey

func (s *Shell) ExpandKey(key string) (string, error)

ExpandKey expands the key of an element of an associative array in arithmetic, as ExpandIndex does for an index, but as a word with no field splitting, as expand_subscript_string of bash does. It implements arith.KeyExpander.

func (*Shell) ExpandString

func (s *Shell) ExpandString(text string) (string, error)

ExpandString expands text as bash expands the value of BASH_ENV or ENV: parameters, command substitution and arithmetic, with no splitting and no globbing.

func (*Shell) Export

func (s *Shell) Export(name, value string) error

Export sets the variable name to value and marks it for the environment of the commands that the shell starts, as export name=value does.

func (*Shell) Finish

func (s *Shell) Finish() int

Finish ends an interactive shell, as bash does: it runs the trap EXIT and saves the history. It returns the status that the shell ends with.

func (*Shell) HandleSignals

func (s *Shell) HandleSignals()

HandleSignals makes the shell at the top receive the signals that other processes send to hail, and act on them as bash does: the traps run at the next safe point, an interactive shell ignores SIGTERM and SIGQUIT, and a signal that ends the process runs the trap EXIT first. It also records the signals that hail ignored when it started: a shell that is not interactive keeps them ignored, as trap cannot change them. An interactive shell keeps ignored those that bash does not handle itself as it starts (softEntrySignal). Call it once, after the options of the command line and before the program. A shell that runs inside another program, such as a test, does without it, and then a signal to $$ goes to the process.

func (*Shell) History

func (s *Shell) History() []string

History returns the entries of the history, the oldest first.

func (*Shell) HistoryVersion

func (s *Shell) HistoryVersion() int

HistoryVersion counts the changes to the history that are not an entry added at its end, such as history -c, -d and -r. A line editor that copies the history copies it again when the count changes.

func (*Shell) Home

func (s *Shell) Home(name string) (string, bool)

Home returns the home directory of the user named name, or $HOME for "". With HOME unset, ~ gives the home directory of the user of the process, as in bash. It implements expand.Env.

The shell reads /etc/passwd through its namespace (D23), and not through the C library, so a user that only a directory service such as LDAP knows has no home directory here. A system with no /etc/passwd, such as Windows or a browser, knows only $HOME.

func (*Shell) ImportOptions

func (s *Shell) ImportOptions()

ImportOptions turns on the options of set -o that SHELLOPTS names, and the options of shopt that BASHOPTS names, when the environment of the shell gave them, as bash does as it starts (initialize_shell_options and initialize_bashopts). bash does this after it applies the options of its command line, -O and +O too, so the environment can only turn options on. A name that set does not know is an error, which ImportOptions prints on stderr. A name that shopt does not know is left out without an error, as in bash.

func (*Shell) Incomplete

func (s *Shell) Incomplete(text string) bool

Incomplete reports whether text, the lines that the user typed so far, needs more lines before it runs, as bash shows PS2 then. A text that is wrong is complete: it runs, and the shell reports the error.

func (*Shell) Interrupt

func (s *Shell) Interrupt()

Interrupt abandons the command that the shell runs, as Ctrl-C does in an interactive bash: the shell stops before the next command of the list or of a loop, with status 130. A job of & goes on. Interrupt is safe to call from another goroutine, such as the one that receives SIGINT.

func (*Shell) IsAssoc

func (s *Shell) IsAssoc(name string) bool

IsAssoc reports whether name is an associative array. It implements arith.Env.

func (*Shell) LineEditing

func (s *Shell) LineEditing() bool

LineEditing reports whether the shell edits its lines now: set -o emacs or set -o vi is on. --noediting and set +o emacs turn it off, and bash then reads its lines without readline.

func (*Shell) LineInterrupted

func (s *Shell) LineInterrupted() bool

LineInterrupted records that the user gave up the line with Ctrl-C at the prompt of the line editor: $? is 130, as in bash. The trap of SIGINT then runs, as bash runs it when readline gives up the line. It reports whether the shell must end, because the trap ran exit. Finish then gives the status.

func (*Shell) LoadHistory

func (s *Shell) LoadHistory()

LoadHistory reads the history file, as an interactive shell does after its startup files.

func (*Shell) Lookup

func (s *Shell) Lookup(name string) expand.Var

Lookup returns the variable name, or nil. It implements expand.Env.

func (*Shell) Names

func (s *Shell) Names(prefix string) []string

Names returns the names of the variables that start with prefix and are set, sorted. It implements expand.Env.

func (*Shell) Param

func (s *Shell) Param(name string) (string, bool)

Param returns the value of a variable or a special parameter, for expansion. It implements expand.Env.

func (*Shell) Positional

func (s *Shell) Positional() []string

Positional returns the positional parameters. It implements expand.Env.

func (*Shell) Prompt

func (s *Shell) Prompt(name string) string

Prompt returns the value of the prompt variable name, such as PS1, PS2, PS0 or PS4, expanded as bash expands a prompt. \[ and \] become the bytes 1 and 2, which mark text that takes no width on the screen. It returns "" when the variable is not set. An error of the expansion is printed, and the prompt then shows its text after the first pass, as in bash.

func (*Shell) ReadBindings

func (s *Shell) ReadBindings(name, text string)

ReadBindings reads text, the lines of an inputrc file, over the key bindings, as bind -f reads a file. name names the text in the messages. config.yaml gives its key bindings this way, after the inputrc file of the user (D14).

func (*Shell) ReadCommandLine

func (s *Shell) ReadCommandLine() (string, error)

ReadCommandLine reads one line of a command from descriptor 0, for an interactive shell that reads its commands with no line editor. It reads one byte at a time, so that a command that reads descriptor 0 finds the rest of the input. It returns the line with its new line, or io.EOF with the text that came before the end of the input.

While it waits, it acts on signals as bash does when it reads a line without readline. Ctrl-C ends the line on the screen and gives up the line, with ErrLineInterrupted. The trap of any other signal runs at once, and the read goes on.

func (*Shell) RefName

func (s *Shell) RefName(name string) (string, bool)

RefName returns the value of the name reference name, the name that it refers to, as ${!name} gives it. It implements expand.NameRefs.

For a chain of references, it is the name at the end of the chain, as in bash.

func (*Shell) Restrict

func (s *Shell) Restrict()

Restrict turns on the restrictions of a restricted shell, as bash does after its startup files, and set -r does at once. The variables of restrictedVars become readonly, with no value when they had none.

func (*Shell) Restricted

func (s *Shell) Restricted() bool

Restricted reports whether the restrictions are on.

func (*Shell) Run

func (s *Shell) Run(r io.Reader) int

Run reads the program from r and runs it, one complete command at a time. It returns the exit status of the shell. Run reads r one byte at a time, so that a child that reads the same input finds the rest of it, as in bash.

func (*Shell) RunInteractive

func (s *Shell) RunInteractive(text string) bool

RunInteractive runs text, one command that the user typed, with its lines, as an interactive bash runs it: it expands the history references, adds the text to the history, writes PS0, and runs the text. A syntax error or a failed expansion does not end the shell. It reports whether the shell must end, because the text ran exit. Finish then gives the status.

func (*Shell) RunKeyCommand

func (s *Shell) RunKeyCommand(command string, l KeyLine) KeyLine

RunKeyCommand runs command, the shell command that bind -x bound to a key, for the line editor, as bash does. READLINE_LINE holds the line, READLINE_POINT the cursor and READLINE_MARK the mark. READLINE_ARGUMENT holds the numeric argument, only when the user typed one. RunKeyCommand returns the line, the cursor and the mark as the command left those variables, each within the line, and unsets them. Count and CountGiven come back as they went in.

A command that runs exit ends only the command, because the editor has no way to end the shell.

func (*Shell) RunStdin

func (s *Shell) RunStdin() int

RunStdin reads the program from descriptor 0 of the shell and runs it, as Run does. A command that changes descriptor 0, such as exec <file, also changes where the program comes from, as in bash.

func (*Shell) RunString

func (s *Shell) RunString(src string) int

RunString runs the program src, as Run does.

func (*Shell) SetAlias

func (s *Shell) SetAlias(name, value string)

SetAlias defines the alias name, as alias name=value does.

func (*Shell) SetElement

func (s *Shell) SetElement(name, key string, value int64) error

SetElement sets the element of the array name at key to the number value. It implements arith.Env.

func (*Shell) SetInteractive

func (s *Shell) SetInteractive(on bool)

SetInteractive records whether the shell is interactive, which puts i in $-. A shell that is not interactive unsets PS1 and PS2. An interactive shell turns on the history, its expansion and the aliases, sets PS1 when it is not set, and sets the variables of the history, as bash does before it reads its startup files.

func (*Shell) SetKeyBinder

func (s *Shell) SetKeyBinder(b KeyBinder)

SetKeyBinder gives the shell the line editor of its terminal, so that each change to the key bindings goes to it, as well as to the model that bind prints. The editor read the defaults of readline and the inputrc file of the user itself. SetKeyBinder then gives it the bindings that bash adds to those of readline, the changes that waited for it, such as those of bind in a startup file and of config.yaml, and the editing mode. A nil b takes the editor away.

func (*Shell) SetLetter

func (s *Shell) SetLetter(c byte, on bool) error

SetLetter turns the option of set with the letter c on or off, as set -e and the command line do.

func (*Shell) SetLineEditor

func (s *Shell) SetLineEditor(edit func(prompt, text string) (string, error))

SetLineEditor gives the shell the line editor of its terminal, for read -e. edit shows prompt, starts the line with text, as read -i gives it, and returns the line that the user typed, without its new line, or an error at the end of the input. A nil edit takes the editor away.

func (*Shell) SetOption

func (s *Shell) SetOption(name string, on bool) error

SetOption turns the option of set -o name on or off, as set -o and the command line do. vi and emacs set the editing mode of readline, as in bash. ignoreeof sets IGNOREEOF to 10, and turning it off unsets IGNOREEOF, as in bash.

func (*Shell) SetPromptWaker

func (s *Shell) SetPromptWaker(wake func() bool)

SetPromptWaker gives the shell wake, which the shell calls from any goroutine when a signal reaches the shell at the top, and when a job changes with set -b. wake asks the line editor to run AtPrompt while it waits for a key, and reports whether the editor waits. When it does not, the shell acts as it does without wake: it takes the signal at its next safe point, and prints the notice at once. A nil wake takes it away.

func (*Shell) SetStdinMode

func (s *Shell) SetStdinMode(on bool)

SetStdinMode records that the shell reads its program from standard input, which puts s in $-.

func (*Shell) SetTerminal

func (s *Shell) SetTerminal(f *os.File) bool

SetTerminal gives the shell at the top the terminal f, for job control, as an interactive bash takes its terminal when it starts: hail leads a process group of its own, and puts it in the foreground of f. It reports false, after the warnings of bash, when the terminal cannot be taken, and the shell then runs without job control. Call it once, at start-up, for an interactive shell.

Windows has no process groups that a terminal moves between, and no stops. There SetTerminal turns job control off and prints nothing, and the shell keeps its jobs, wait and kill without it.

func (*Shell) SetVar

func (s *Shell) SetVar(name string, value int64) error

SetVar sets the variable name to the number value. It implements arith.Env.

func (*Shell) Shopt

func (s *Shell) Shopt(name string, on bool) error

Shopt turns the option of shopt name on or off, as shopt -s and the command line option -O do.

func (*Shell) ShoptOn

func (s *Shell) ShoptOn(name string) bool

ShoptOn reports whether the option of shopt name is on.

func (*Shell) SourceFile

func (s *Shell) SourceFile(path string) bool

SourceFile runs the file at path in the shell, as . does, if the file exists, as bash runs a startup file. It reports whether the shell must end, because the file ran exit.

func (*Shell) StackDir

func (s *Shell) StackDir(n int, fromBottom bool) (string, bool)

StackDir returns the directory n of the directory stack, from the top, or from the bottom with fromBottom. The top is the working directory. It implements expand.DirStack.

func (*Shell) Status

func (s *Shell) Status() int

Status returns $?, the status of the last command.

func (*Shell) Stderr

func (s *Shell) Stderr() io.Writer

Stderr returns a writer of descriptor 2 of the shell, whatever file it is at the time of the write, for the prompts of a shell that no line editor draws.

func (*Shell) Stdin

func (s *Shell) Stdin() io.Reader

Stdin returns a reader of descriptor 0 of the shell, whatever file it is at the time of the read. A command such as exec <file changes it.

func (*Shell) SyncEditingMode

func (s *Shell) SyncEditingMode()

SyncEditingMode takes the editing mode of the editor into the model and into the options vi and emacs. A key can change the mode while the editor reads a line, as Ctrl-Alt-J does in emacs mode, and readline then holds the mode that set -o and bind -v show, as in bash.

func (*Shell) Var

func (s *Shell) Var(name string) (string, error)

Var returns the value of the variable name for arithmetic. A variable that is not set is "", or an error under set -u. It implements arith.Env.

func (*Shell) Warn

func (s *Shell) Warn(msg string, command bool)

Warn prints a problem of arithmetic that does not stop it, with the name of the command, such as "((", before it when command is true and the command is (( or let. It implements arith.Warner.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL