Go library
How to embed gnux in a Go program: every tool's engine is an importable package under core/ that removes, copies, lists, counts or tails files with GNU semantics in your own process, without spawning anything. This guide covers building an engine from its Options (whose zero value keeps every safeguard on), wiring it to core.Streams to capture output in a bytes.Buffer or silence it, injecting prompts, removals, clocks and the environment, telling the three kinds of error apart with errors.Is and errors.As, running any tool by name with cmd.RunTool, running whole portable scripts with cmd.NewShell, and embedding the entire command line with cmd.Main. It ends with seventeen complete programs, each of which was compiled and run against the module.
Add the module
go get github.com/braswelljr/gnuxThe engines under core/ depend only on the standard library, github.com/mattn/go-isatty, golang.org/x/sys (system calls Go's standard library does not wrap, on Windows and the BSDs) and golang.org/x/crypto (BLAKE2b for b2sum); all are pure Go. Cobra and pflag are linked in only if you import github.com/braswelljr/gnux/cmd (for RunTool, NewShell and Main).
Go 1.26 or newer is required.
The shape of every engine
Each tool's package has the same four pieces:
| Piece | Example | What it is |
|---|---|---|
Name | rm.Name == "rmx" | The command name, used as the prefix of every diagnostic |
Options | rm.Options{Recursive: true} | The flags, as a struct |
New(opts, streams) | rm.New(opts, core.Stdio()) | Builds the engine |
Run(args) error | engine.Run([]string{"build"}) | Runs it against the operands |
| Package | Tool | Notable extras |
|---|---|---|
core/basename | basenamex | Base(name, suffix) |
core/cat | catx | |
core/cp | cpx | PromptFn, Copy(src, dst), PreserveAll(), Deref* constants |
core/dirname | dirnamex | Dir(name) |
core/echo | echox | Parse(args) for GNU echo's option rules |
core/env | envx | Environ, SplitString, ExitCanceled/ExitCannotInvoke/ExitNotFound |
core/head | headx | DefaultLines, ParseSize |
core/ln | lnx | PromptFn |
core/ls | lsx | IsTerminal, TermWidth, Getenv, Now, Location, Format*/Sort* constants |
core/mkdir | mkdirx | |
core/mv | mvx | PromptFn, RenameFn |
core/pwd | pwdx | Getenv, Getwd |
core/realpath | realpathx | Mode* constants |
core/rm | rmx | PromptFn, RemoveFn, Prompt* constants |
core/rmdir | rmdirx | |
core/sleep | sleepx | Sleep (no Options: New(streams)), Total(args), Forever |
core/tail | tailx | RunContext(ctx, args), Follow* constants, DefaultLines |
core/touch | touchx | Now |
core/wc | wcx | Total* constants |
core/yes | yesx | No Options: New(streams), Line(args) |
core/shell | gnux shell | New(opts, exec, streams), Run, RunString, Eval, Set, SetArgs, Incomplete |
truex and falsex have no engine: in Go they are return nil and return core.ErrFailed.
Full API documentation is on pkg.go.dev.
Options and the zero value
Options mirrors the GNU flags. For the tools whose flags are switches, the zero value is the plain command, safeguards included:
rm.Options{}isrmx: no recursion, default prompting, and the/failsafe on. The failsafe is controlled byNoPreserveRoot, a negative name precisely so that forgetting to set it keeps you safe.cp.Options{}iscpx: no recursion, overwrite allowed, links followed as GNUcpdoes.ls.Options{}islsx: names sorted bytewise, hidden files skipped, columns on a terminal and one per line otherwise.
Write only the flags you want: rm.Options{Recursive: true, Force: true} is rmx -rf, everything else as plain rm.
Counts are the exception. In head.Options and tail.Options, Count is the number the command line passes after -n, and the adapter fills in 10 when you give none. In Go, head.Options{} selects zero lines and prints nothing. Set the count explicitly:
_ = head.New(head.Options{Count: head.DefaultLines}, s).Run(nil)Likewise wc.Options{} prints lines, words and bytes, as wcx with no flags does, while wc.Options{Lines: true} is wcx -l.
Streams
An engine reads and writes only through the core.Streams it is given, never through os.Stdin or os.Stdout directly:
type Streams struct {
In io.Reader
Out io.Writer
Err io.Writer
}| Constructor | Use it to |
|---|---|
core.Stdio() | Behave like the command line: the process's own streams |
core.Discard() | Keep only side effects and the returned error |
core.Streams{In: ..., Out: &buf, Err: &errs} | Capture output and diagnostics, or feed input |
All three fields must be non-nil. The safe way to override one is to start from core.Discard() and replace the field you care about, as program 13 shows.
Diagnostics on Err are GNU's exact words, prefixed with the tool name: rmx: cannot remove 'x': No such file or directory. Prompts (rmx: remove regular file 'x'?) are written to Err and answered from In, unless you inject an answer function.
Injection points
Engines expose exported fields for everything that would otherwise need a terminal, a clock or the real environment. Set them after New and before Run.
| Field | On | Replaces |
|---|---|---|
PromptFn func(question string) bool | rm.Rm, cp.Cp, mv.Mv, ln.Ln | Reading y/n from In |
RemoveFn func(path string) error | rm.Rm | os.Remove; also disables the os.RemoveAll fast path so every entry reaches it |
RenameFn func(old, new string) error | mv.Mv | os.Rename |
Now func() time.Time | touch.Touch, ls.Ls | The clock |
Getenv func(string) string | ls.Ls, pwd.Pwd, shell.Shell | os.Getenv |
Environ func() []string | env.Env | os.Environ |
Getwd func() (string, error) | pwd.Pwd | os.Getwd |
IsTerminal bool, TermWidth func() int | ls.Ls | Terminal detection |
Sleep func(time.Duration) | sleep.Sleep | The actual pause |
HomeDir func() (string, error) | shell.Shell | os.UserHomeDir |
Exec shell.ExecFunc | shell.Shell | The command set |
A PromptFn receives the question exactly as rmx would print it, without the rmx: prefix, for example remove regular empty file 'logs/app.log'?.
Errors
Every engine follows one convention:
| Returned error | Meaning | CLI exit status | What to do |
|---|---|---|---|
nil | Success | 0 | Carry on |
core.ErrFailed | It ran; one or more operands failed; diagnostics are already on Err | 1 | Treat as failure; do not print the error again |
*core.UsageError | The call was wrong: no operands, an invalid value | 1 | Fix the call; Msg says what was wrong |
*core.ExitError | A specific status (lsx 2, envx 125 to 127) | Code | Read Code |
Use errors.Is(err, core.ErrFailed) for the first and errors.As for the other two; program 14 does all three.
A failing operand never stops the rest, so ErrFailed means "some" not "all": check the filesystem or the diagnostics if you need to know which.
Running tools by name: cmd.RunTool
When you have a command line as data (a plugin host, a chat bot, a job runner), skip the Options structs and run a tool by name:
status, ok := cmd.RunTool("wc", []string{"-l", "go.mod"}, s)Either the gnux name or the GNU name works. ok is false when no tool has that name. status is the exit status the command line would give, and usage errors are printed to the error stream with the Try 'rmx --help' hint, as program 8 shows.
Running scripts: cmd.NewShell
cmd.NewShell(opts, streams) builds a gnux shell whose commands are the registered tools, run in-process:
| Method | Does |
|---|---|
Set(name, value) | Defines a shell variable before running |
RunString(script) / Run(reader) | Runs a whole script, restores the working directory afterwards, and returns nil or *core.ExitError with the last status |
SetArgs(name, args) | Gives the script its $0 and its arguments ($1, $2, ..., "$@") |
Eval(command) int | Runs one command (a line, or a whole if, loop or case) and keeps every bit of state (variables, cd), for REPL-style hosts |
shell.Options{ErrExit: true, NoUnset: true} is -eu. shell.Incomplete(text) reports whether text is the start of a command that more lines would finish, which is how a host that reads line by line knows to ask for another before calling Eval. Shell.LoopLimit stops a loop after that many turns, for a host that has no way to interrupt a script. For a custom command set, build the shell with shell.New(opts, exec, streams) and your own ExecFunc, as program 16 does.
cd changes the process-wide working directory while a script runs, because tools resolve relative paths against it. Do not run two shells concurrently in one process.
Embedding the command line: cmd.Main
cmd.Main(argv, streams) is the whole gnux command line as a function. It picks the tool from argv[0] exactly as the binary does and returns the exit status instead of calling os.Exit. Program 12 is a complete re-implementation of the gnux binary in eight lines.
Concurrency notes
rm.Runalready fans out across top-level arguments when no prompting or-vis involved; you rarely need your own goroutines around it.- Engines are not meant to be shared between goroutines: build one per call. They are cheap.
core.Diagis safe for concurrent use, so diagnostics from parallel work never interleave mid-line.- A shell's
cdaffects the whole process; keep shells sequential.
Complete programs
Each program below is a main package in a module whose go.mod requires github.com/braswelljr/gnux. All seventeen were built with go build and go vet and run against real files; the outputs shown are real.
1. Cleanup: rmx -rf build dist
// Command cleanup removes build outputs the way `rmx -rf build dist` would.
package main
import (
"errors"
"log"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/rm"
)
func main() {
engine := rm.New(rm.Options{Recursive: true, Force: true}, core.Stdio())
if err := engine.Run([]string{"build", "dist"}); err != nil {
if errors.Is(err, core.ErrFailed) {
// The diagnostics are already on stderr; just set the status.
log.Fatal("cleanup incomplete")
}
log.Fatal(err)
}
}2. Capture a listing: lsx -1A DIR
// Command listing captures `lsx -1 DIR` into a slice of names.
package main
import (
"bytes"
"fmt"
"log"
"os"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/ls"
)
func main() {
dir := "."
if len(os.Args) > 1 {
dir = os.Args[1]
}
var out, errs bytes.Buffer
s := core.Streams{In: strings.NewReader(""), Out: &out, Err: &errs}
engine := ls.New(ls.Options{Format: ls.FormatSingle, AlmostAll: true}, s)
if err := engine.Run([]string{dir}); err != nil {
log.Fatalf("lsx failed: %v\n%s", err, errs.String())
}
names := strings.Fields(out.String())
fmt.Printf("%d entries in %s\n", len(names), dir)
for _, n := range names {
fmt.Println(" -", n)
}
}2 entries in src
- a.txt
- sub3. Dry run with RemoveFn
// Command dryrun shows what `rmx -r` would delete without deleting anything.
package main
import (
"fmt"
"log"
"os"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/rm"
)
func main() {
engine := rm.New(rm.Options{Recursive: true}, core.Discard())
// RemoveFn replaces the real unlink, and disables the os.RemoveAll fast
// path so that every entry is reported to it.
engine.RemoveFn = func(path string) error {
fmt.Println("would remove", path)
return nil
}
if err := engine.Run(os.Args[1:]); err != nil {
log.Fatal(err)
}
}would remove src/a.txt
would remove src/sub/b.txt
would remove src/sub
would remove srcNothing is deleted: RemoveFn received every path in post-order and returned nil.
4. Answer prompts from code with PromptFn
// Command confirm answers rmx's interactive prompts from Go: it removes
// only the *.log files under a directory, keeping everything else.
package main
import (
"fmt"
"log"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/rm"
)
func main() {
engine := rm.New(rm.Options{
Recursive: true,
Interactive: rm.PromptAlways, // rmx -ri
}, core.Stdio())
// PromptFn receives the exact question rmx would print and decides.
engine.PromptFn = func(question string) bool {
yes := strings.Contains(question, "descend into") ||
strings.Contains(question, ".log'")
fmt.Printf("%-60s %v\n", question, yes)
return yes
}
if err := engine.Run([]string{"logs"}); err != nil {
log.Fatal(err)
}
}descend into directory 'logs'? true
remove regular empty file 'logs/app.log'? true
remove regular empty file 'logs/keep.txt'? false
descend into directory 'logs/old'? true
remove regular empty file 'logs/old/x.log'? true
remove directory 'logs/old'? falselogs/keep.txt and the directories survive. Declining a directory that still has entries is how a selective delete keeps its parents.
5. A pinned clock and a usage error: touchx
// Command stamp sets reproducible timestamps, like `touchx -d` for an archive.
package main
import (
"errors"
"fmt"
"log"
"os"
"time"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/touch"
)
func main() {
// A pinned clock instead of time.Now: every file gets the same time.
release := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
engine := touch.New(touch.Options{}, core.Stdio())
engine.Now = func() time.Time { return release }
if err := engine.Run([]string{"a.txt", "b.txt"}); err != nil {
log.Fatal(err)
}
info, err := os.Stat("a.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("a.txt modified:", info.ModTime().UTC())
// A bad date is a usage error, not a failure.
err = touch.New(touch.Options{Date: "next tuesday"}, core.Discard()).Run([]string{"c.txt"})
var usage *core.UsageError
if errors.As(err, &usage) {
fmt.Println("usage error:", usage.Msg)
}
}a.txt modified: 2025-01-01 00:00:00 +0000 UTC
usage error: invalid date format 'next tuesday'6. Count in-memory text: wcx -lw
// Command count runs `wcx -lw` over in-memory text, with no files at all.
package main
import (
"bytes"
"fmt"
"log"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/wc"
)
func main() {
text := "the quick brown fox\njumps over\nthe lazy dog\n"
var out bytes.Buffer
s := core.Streams{In: strings.NewReader(text), Out: &out, Err: &out}
// No operands means standard input, exactly as on the command line.
if err := wc.New(wc.Options{Lines: true, Words: true}, s).Run(nil); err != nil {
log.Fatal(err)
}
fmt.Printf("wcx says: %q\n", out.String())
}wcx says: " 3 9\n"7. Backup with mkdirx -p and cpx -av
// Command backup copies a tree with `cpx -av` semantics and reports each file.
package main
import (
"errors"
"fmt"
"os"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/cp"
"github.com/braswelljr/gnux/core/mkdir"
)
func main() {
streams := core.Stdio()
// mkdirx -p backups
if err := mkdir.New(mkdir.Options{Parents: true}, streams).Run([]string{"backups"}); err != nil {
os.Exit(1)
}
// cpx -a -v src backups/src : -a is -dR --preserve=all
engine := cp.New(cp.Options{
Recursive: true,
Verbose: true,
Preserve: cp.PreserveAll(),
Dereference: cp.DerefNever,
}, streams)
err := engine.Run([]string{"src", "backups/src"})
switch {
case err == nil:
fmt.Println("backup complete")
case errors.Is(err, core.ErrFailed):
fmt.Fprintln(os.Stderr, "backup incomplete; see the messages above")
os.Exit(1)
default: // *core.UsageError: the call itself was wrong
fmt.Fprintln(os.Stderr, "bad call:", err)
os.Exit(2)
}
}'src' -> 'backups/src'
'src/a.txt' -> 'backups/src/a.txt'
'src/sub' -> 'backups/src/sub'
'src/sub/b.txt' -> 'backups/src/sub/b.txt'
backup complete8. Run any tool by name: cmd.RunTool
// Command runtool runs any gnux tool by name, the way a plugin host might.
package main
import (
"bytes"
"fmt"
"os"
"strings"
"github.com/braswelljr/gnux/cmd"
"github.com/braswelljr/gnux/core"
)
func main() {
var out, errs bytes.Buffer
s := core.Streams{In: strings.NewReader(""), Out: &out, Err: &errs}
// Either name works: "wcx" or "wc".
status, ok := cmd.RunTool("wc", []string{"-l", "go.mod"}, s)
if !ok {
fmt.Fprintln(os.Stderr, "no such tool")
os.Exit(2)
}
fmt.Printf("status=%d stdout=%q stderr=%q\n", status, out.String(), errs.String())
out.Reset()
errs.Reset()
status, _ = cmd.RunTool("rmx", []string{"--bogus"}, s)
fmt.Printf("status=%d stderr=%q\n", status, errs.String())
_, ok = cmd.RunTool("frobx", nil, s)
fmt.Println("frobx found:", ok)
}status=0 stdout="1 go.mod\n" stderr=""
status=1 stderr="rmx: unrecognized option '--bogus'\nTry 'rmx --help' for more information.\n"
frobx found: false9. Run a script in-process: cmd.NewShell
// Command build runs a portable gnux shell script in-process.
package main
import (
"errors"
"fmt"
"os"
"github.com/braswelljr/gnux/cmd"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/shell"
)
const script = `
# Stage a release directory.
rmx -rf $OUT
mkdirx -p $OUT/bin $OUT/docs
cpx README.md $OUT/docs/
echox "version $VERSION" > $OUT/VERSION
lsx -1 $OUT
`
func main() {
sh := cmd.NewShell(shell.Options{ErrExit: true}, core.Stdio())
sh.Set("OUT", "dist")
sh.Set("VERSION", "1.2.3")
err := sh.RunString(script)
var exit *core.ExitError
switch {
case err == nil:
fmt.Println("staged")
case errors.As(err, &exit):
fmt.Fprintln(os.Stderr, "script failed with status", exit.Code)
os.Exit(exit.Code)
default:
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}VERSION
bin
docs
staged10. A REPL host with Eval
// Command repl drives a gnux shell one line at a time, keeping its state,
// as a chat bot, an editor plugin or the web playground would.
package main
import (
"bytes"
"fmt"
"strings"
"github.com/braswelljr/gnux/cmd"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/shell"
)
func main() {
var out bytes.Buffer
sh := cmd.NewShell(shell.Options{}, core.Streams{
In: strings.NewReader(""),
Out: &out,
Err: &out,
})
lines := []string{
"mkdirx -p sandbox",
"cd sandbox",
"GREETING='hello from gnux'",
"echox $GREETING > hello.txt",
"catx hello.txt | wcx -w",
"catx missing.txt",
"echox last status was $?",
}
for _, line := range lines {
out.Reset()
status := sh.Eval(line)
fmt.Printf("$ %s\n%s[status %d]\n", line, out.String(), status)
}
}$ mkdirx -p sandbox
[status 0]
$ cd sandbox
[status 0]
$ GREETING='hello from gnux'
[status 0]
$ echox $GREETING > hello.txt
[status 0]
$ catx hello.txt | wcx -w
3
[status 0]
$ catx missing.txt
catx: missing.txt: No such file or directory
[status 1]
$ echox last status was $?
last status was 1
[status 0]11. Follow a log with a deadline: tailx -F and RunContext
// Command follow tails a log for a fixed time, like `tailx -f` with a deadline.
package main
import (
"context"
"log"
"os"
"time"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/tail"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
engine := tail.New(tail.Options{
Count: 5, // -n 5 (the CLI default is 10)
Follow: tail.FollowName, // --follow=name: survives rotation
Retry: true, // --retry
SleepInterval: 200 * time.Millisecond, // -s 0.2
}, core.Stdio())
if err := engine.RunContext(ctx, os.Args[1:]); err != nil {
log.Fatal(err)
}
}first
secondRunContext returns when the context is canceled, when the PID process exits, or when no file is left to follow. It returns core.ErrFailed if any operand failed along the way, including a file that was missing when following began.
12. The whole command line: cmd.Main
// Command embed is a whole gnux command line inside another program: it
// hands its own arguments to cmd.Main and exits with the status it returns.
package main
import (
"os"
"github.com/braswelljr/gnux/cmd"
"github.com/braswelljr/gnux/core"
)
func main() {
// argv[0] picks the tool, exactly as for the real binary: "gnux" gives
// the multi-call root, "rmx" (or "rm") would give that tool directly.
argv := append([]string{"gnux"}, os.Args[1:]...)
os.Exit(cmd.Main(argv, core.Stdio()))
}go build -o mygnux . && ./mygnux wcx -l go.mod && ./mygnux rmx1 go.mod
rmx: missing operand
Try 'rmx --help' for more information.13. Three ways to wire streams: catx
// Command quiet shows the three ways to give an engine its streams.
package main
import (
"bytes"
"fmt"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/cat"
)
func main() {
// 1. The process's own stdin, stdout and stderr.
_ = cat.New(cat.Options{}, core.Stdio()).Run([]string{"go.mod"})
// 2. Discard everything; only the side effects and the error matter.
err := cat.New(cat.Options{}, core.Discard()).Run([]string{"missing.txt"})
fmt.Println("silenced error:", err)
// 3. Start from Discard and override only what you need. All three
// fields must be non-nil, which Discard guarantees.
var numbered bytes.Buffer
s := core.Discard()
s.In = strings.NewReader("alpha\n\nbeta\n")
s.Out = &numbered
_ = cat.New(cat.Options{NumberNonblank: true}, s).Run(nil) // catx -b
fmt.Print(numbered.String())
}module x
silenced error: command failed
1 alpha
2 beta14. Telling errors apart
// Command errs shows the three kinds of error an engine returns.
package main
import (
"errors"
"fmt"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/ls"
"github.com/braswelljr/gnux/core/rm"
)
func explain(tool string, err error) {
var usage *core.UsageError
var exit *core.ExitError
switch {
case err == nil:
fmt.Printf("%s: success (exit 0)\n", tool)
case errors.Is(err, core.ErrFailed):
fmt.Printf("%s: ran, something failed and was reported (exit 1)\n", tool)
case errors.As(err, &usage):
fmt.Printf("%s: usage error %q (exit 1, plus a --help hint on the CLI)\n", tool, usage.Msg)
case errors.As(err, &exit):
fmt.Printf("%s: specific status %d\n", tool, exit.Code)
default:
fmt.Printf("%s: unexpected error: %v\n", tool, err)
}
}
func main() {
quiet := core.Discard()
explain("rmx -f nothing", rm.New(rm.Options{Force: true}, quiet).Run([]string{"nothing"}))
explain("rmx nothing", rm.New(rm.Options{}, quiet).Run([]string{"nothing"}))
explain("rmx (no operands)", rm.New(rm.Options{}, quiet).Run(nil))
explain("lsx nothing", ls.New(ls.Options{}, quiet).Run([]string{"nothing"}))
}rmx -f nothing: success (exit 0)
rmx nothing: ran, something failed and was reported (exit 1)
rmx (no operands): usage error "missing operand" (exit 1, plus a --help hint on the CLI)
lsx nothing: specific status 215. Paths without a filesystem: basenamex, dirnamex, realpathx
// Command paths uses the text-only helpers and the realpath engine.
package main
import (
"bytes"
"fmt"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/basename"
"github.com/braswelljr/gnux/core/dirname"
"github.com/braswelljr/gnux/core/realpath"
)
func main() {
// Pure functions with GNU's exact rules: no filesystem access.
fmt.Println(basename.Base("/usr/local/bin/gnux", "")) // gnux
fmt.Println(basename.Base("src/main.go", ".go")) // main
fmt.Println(basename.Base("dir/", "")) // dir
fmt.Println(dirname.Dir("/usr/local/bin/gnux")) // /usr/local/bin
fmt.Println(dirname.Dir("file")) // .
fmt.Println(dirname.Dir("/top")) // /
// realpathx -m --relative-to=/srv /srv/app/../app/config.yaml
var out bytes.Buffer
s := core.Discard()
s.Out = &out
engine := realpath.New(realpath.Options{
Mode: realpath.ModeMissing,
RelativeTo: "/srv",
}, s)
if err := engine.Run([]string{"/srv/app/../app/config.yaml"}); err == nil {
fmt.Println(strings.TrimSpace(out.String())) // app/config.yaml
}
}gnux
main
dir
/usr/local/bin
.
/
app/config.yaml16. A sandboxed shell with a custom ExecFunc
// Command sandbox runs user-supplied scripts with only read-only tools
// available, by giving the shell its own ExecFunc.
package main
import (
"fmt"
"os"
"github.com/braswelljr/gnux/cmd"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/shell"
)
var allowed = map[string]bool{
"lsx": true, "ls": true, "catx": true, "cat": true,
"headx": true, "head": true, "tailx": true, "tail": true,
"wcx": true, "wc": true, "echox": true, "echo": true,
}
func main() {
exec := func(name string, args []string, s core.Streams) (int, bool) {
if !allowed[name] {
fmt.Fprintf(s.Err, "sandbox: %s is not allowed\n", name)
return 126, true // found, but refused
}
return cmd.RunTool(name, args, s)
}
sh := shell.New(shell.Options{}, exec, core.Stdio())
err := sh.RunString("lsx -1 | wcx -l; rmx -rf .; echox still here")
if err != nil {
fmt.Fprintln(os.Stderr, "script ended with:", err)
}
}1
sandbox: rmx is not allowed
still hereThe shell reaches tools only through its Exec function, so an allowlist is a complete sandbox for the command set. (It does not restrict cd or redirection, which are the shell's own.)
17. headx and the explicit count
// Command first10 shows that headx's line count must be set explicitly.
package main
import (
"fmt"
"strings"
"github.com/braswelljr/gnux/core"
"github.com/braswelljr/gnux/core/head"
)
func main() {
s := core.Stdio()
// The zero value selects zero lines: nothing is printed.
s.In = strings.NewReader("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n")
_ = head.New(head.Options{}, s).Run(nil)
fmt.Println("---")
// headx with no -n: ask for DefaultLines (10) explicitly.
s.In = strings.NewReader("1\n2\n3\n")
_ = head.New(head.Options{Count: head.DefaultLines}, s).Run(nil)
}---
1
2
3The first call prints nothing: Count is zero. The second prints up to head.DefaultLines lines.
See also
- Portable scripting for the language the shell programs run.
- Troubleshooting for what each diagnostic means.
- Requirements, section 6 (the Go library), and workflows WF-4 and WF-5 in the user workflows.
- Workflows for how the engines are built inside.
Getting started
This guide takes you from nothing to a working gnux installation: installing the binary with go install, make, install.sh or Docker, turning each of the 108 tools into a command of its own by linking its name to the binary, and running your first commands in both invocation forms. It also covers the GNU-name aliases that let scripts written for the GNU tools run unchanged, the --help, --version and --list options every installation has, and how to check that everything is wired up correctly.
Node and npm
gnux on npm: one development dependency that puts rmx, cpx, mkdirx, lsx and every other tool on the PATH of your package scripts, with GNU's flags and messages on Linux, macOS and Windows alike. It replaces rimraf, mkdirp, cpy-cli, del-cli, shx and cross-env with the commands you already know, and runs the native binary, not JavaScript.