add command lists (;, &&, ||) and $?
- split input at unquoted ;, && and || and run the commands like sh;
variables are expanded per command when it runs
- $? and ${?} expand to the exit status of the last command,
exit/quit without argument use it
- syntax errors for missing commands around operators (status 2)
- "command not found" message instead of the raw exec error, no more
"exit status N" message when a command fails
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b602e17622
commit
f5c14dff90
3 files changed
+307
-20
No files matched your search
@@ -12,6 +12,7 @@ import (
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unicode"
|
||||
@@ -216,6 +217,9 @@ func expandVar(s string) (string, int, error) {
|
||||
return "", 0, errors.New("missing } in variable reference")
|
||||
}
|
||||
name, def, hasDef := strings.Cut(s[2:end], ":-")
|
||||
if name == "?" {
|
||||
return strconv.Itoa(lastStatus), end + 1, nil
|
||||
}
|
||||
if !isVarName(name) {
|
||||
return "", 0, fmt.Errorf("bad substitution: %s", s[:end+1])
|
||||
}
|
||||
@@ -229,6 +233,10 @@ func expandVar(s string) (string, int, error) {
|
||||
return value, end + 1, nil
|
||||
}
|
||||
|
||||
if len(s) > 1 && s[1] == '?' {
|
||||
return strconv.Itoa(lastStatus), 2, nil
|
||||
}
|
||||
|
||||
n := 1
|
||||
for n < len(s) && isVarNameByte(s[n], n == 1) {
|
||||
n++
|
||||
@@ -693,13 +701,8 @@ func runScript(r io.Reader) int {
|
||||
for {
|
||||
line, err := readLine(r)
|
||||
if trimmed := strings.TrimSpace(line); trimmed != "" && !strings.HasPrefix(trimmed, "#") {
|
||||
cmdErr := execInput(line)
|
||||
status = exitStatus(cmdErr)
|
||||
// A command that ran and failed reports its own errors.
|
||||
var exitErr *exec.ExitError
|
||||
if cmdErr != nil && !errors.As(cmdErr, &exitErr) {
|
||||
fmt.Fprintln(os.Stderr, "gosh:", cmdErr)
|
||||
}
|
||||
printError(execInput(line))
|
||||
status = lastStatus
|
||||
}
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
@@ -747,7 +750,7 @@ func exitStatus(err error) int {
|
||||
}
|
||||
return exitErr.ExitCode()
|
||||
}
|
||||
if errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist) {
|
||||
if errors.Is(err, errCommandNotFound) || errors.Is(err, fs.ErrNotExist) {
|
||||
return 127
|
||||
}
|
||||
if errors.Is(err, fs.ErrPermission) {
|
||||
@@ -819,13 +822,142 @@ func interactive() {
|
||||
}
|
||||
|
||||
// Execute the input
|
||||
if err := execInput(line); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
}
|
||||
printError(execInput(line))
|
||||
}
|
||||
}
|
||||
|
||||
// lastStatus is the exit status of the last command ($?).
|
||||
var lastStatus int
|
||||
|
||||
// errCommandNotFound is returned when an external command does not exist.
|
||||
var errCommandNotFound = errors.New("command not found")
|
||||
|
||||
// printError prints an error of a command to stderr. Commands that ran and
|
||||
// failed have already reported the problem themselves, only their exit
|
||||
// status is kept.
|
||||
func printError(err error) {
|
||||
var exitErr *exec.ExitError
|
||||
if err == nil || errors.As(err, &exitErr) {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "gosh:", err)
|
||||
}
|
||||
|
||||
// listItem is a command of a command list together with the operator that
|
||||
// connects it to the previous command ("" for the first one).
|
||||
type listItem struct {
|
||||
op string // "", ";", "&&" or "||"
|
||||
command string
|
||||
}
|
||||
|
||||
// splitList splits input at unquoted ;, && and ||. Quotes, escapes, ${...}
|
||||
// and comments are handled like in splitWords, but nothing is expanded yet:
|
||||
// that happens per command when it runs, so "cd /tmp && echo $PWD" works.
|
||||
func splitList(input string) ([]listItem, error) {
|
||||
var (
|
||||
items []listItem
|
||||
op string
|
||||
start int
|
||||
quote byte
|
||||
escaped bool
|
||||
wordStart = true // the next character starts a word
|
||||
)
|
||||
|
||||
end := len(input)
|
||||
add := func(i int, next string) error {
|
||||
command := input[start:i]
|
||||
if strings.TrimSpace(command) == "" {
|
||||
// "a;" is fine, but an operator needs a command on both sides
|
||||
if next != "" || op == "&&" || op == "||" {
|
||||
if next == "" {
|
||||
next = op
|
||||
}
|
||||
return fmt.Errorf("syntax error near unexpected token `%s'", next)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
items = append(items, listItem{op: op, command: command})
|
||||
return nil
|
||||
}
|
||||
|
||||
scan:
|
||||
for i := 0; i < len(input); i++ {
|
||||
ch := input[i]
|
||||
isWordStart := wordStart
|
||||
wordStart = false
|
||||
switch {
|
||||
case escaped:
|
||||
escaped = false
|
||||
case quote == '\'':
|
||||
if ch == '\'' {
|
||||
quote = 0
|
||||
}
|
||||
case ch == '\\':
|
||||
escaped = true
|
||||
case ch == '$' && i+1 < len(input) && input[i+1] == '{':
|
||||
// Skip ${...} as a whole, like expandVar does
|
||||
if j := strings.IndexByte(input[i:], '}'); j >= 0 {
|
||||
i += j
|
||||
}
|
||||
case quote == '"':
|
||||
if ch == '"' {
|
||||
quote = 0
|
||||
}
|
||||
case ch == '"' || ch == '\'':
|
||||
quote = ch
|
||||
case ch == ' ' || ch == '\t' || ch == '\n':
|
||||
wordStart = true
|
||||
case ch == '#' && isWordStart:
|
||||
end = i
|
||||
break scan
|
||||
case ch == ';',
|
||||
ch == '&' && i+1 < len(input) && input[i+1] == '&',
|
||||
ch == '|' && i+1 < len(input) && input[i+1] == '|':
|
||||
next := input[i : i+1]
|
||||
if ch != ';' {
|
||||
next = input[i : i+2]
|
||||
}
|
||||
if err := add(i, next); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i += len(next) - 1
|
||||
op = next
|
||||
start = i + 1
|
||||
wordStart = true
|
||||
}
|
||||
}
|
||||
|
||||
// An unterminated quote or a trailing \ is reported by splitWords
|
||||
if err := add(end, ""); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// execInput executes a line of input: a list of commands separated by ;, &&
|
||||
// and ||. It returns the error of the last command that was run; errors of
|
||||
// earlier commands are printed. $? is updated after each command.
|
||||
func execInput(input string) error {
|
||||
items, err := splitList(input)
|
||||
if err != nil {
|
||||
lastStatus = 2
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for _, item := range items {
|
||||
if (item.op == "&&" && lastStatus != 0) || (item.op == "||" && lastStatus == 0) {
|
||||
continue
|
||||
}
|
||||
printError(lastErr)
|
||||
lastErr = execCommand(item.command)
|
||||
lastStatus = exitStatus(lastErr)
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// execCommand executes a single simple command.
|
||||
func execCommand(input string) error {
|
||||
// Split the input into the command and its arguments, expanding
|
||||
// variables and ~ on the way.
|
||||
args, err := splitWords(input)
|
||||
@@ -879,7 +1011,7 @@ func execInput(input string) error {
|
||||
fmt.Sscanf(args[1], "%d", &exitCode)
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
os.Exit(0)
|
||||
os.Exit(lastStatus)
|
||||
case "quit":
|
||||
// quit with optional status code
|
||||
if len(args) > 1 {
|
||||
@@ -887,7 +1019,7 @@ func execInput(input string) error {
|
||||
fmt.Sscanf(args[1], "%d", &exitCode)
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
os.Exit(0)
|
||||
os.Exit(lastStatus)
|
||||
case "set":
|
||||
// set VAR=value - set environment variable
|
||||
if len(args) < 2 {
|
||||
@@ -919,8 +1051,8 @@ Built-in commands:
|
||||
cd [dir] - Change directory (cd with no args goes to home)
|
||||
pwd - Print working directory
|
||||
echo [args] - Echo arguments
|
||||
exit [code] - Exit shell with optional status code
|
||||
quit [code] - Quit shell with optional status code
|
||||
exit [code] - Exit shell with status code (default: $?)
|
||||
quit [code] - Quit shell with status code (default: $?)
|
||||
set VAR=val - Set environment variable
|
||||
export VAR=val - Export environment variable
|
||||
help - Show this help
|
||||
@@ -940,6 +1072,8 @@ Features:
|
||||
disabled with $NO_COLOR, TERM=dumb or when output is not a terminal
|
||||
- Environment variable expansion ($VAR, ${VAR}, ${VAR:-default});
|
||||
using an unset variable is an error, use ${VAR:-} for an empty default
|
||||
- Command lists: a ; b (run both), a && b (b only if a succeeded),
|
||||
a || b (b only if a failed); $? is the exit status of the last command
|
||||
- Non-interactive use: gosh -c 'command', gosh script, command | gosh;
|
||||
the exit status is the one of the last command`)
|
||||
return nil
|
||||
@@ -957,5 +1091,9 @@ Features:
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
// Execute the command return the error.
|
||||
return cmd.Run()
|
||||
err = cmd.Run()
|
||||
if errors.Is(err, exec.ErrNotFound) {
|
||||
return fmt.Errorf("%s: %w", sanitize(args[0]), errCommandNotFound)
|
||||
}
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user