Niubash
Bash, native on Windows. No WSL. No VM. No
/mnt/c. No cmdlet dialect. Just the shell your fingers already know — and the one your AI agent actually speaks.
This is the Niubash documentation. Start with the guides, or jump straight into the shell:
C:\Users\you\repo
❯ test -f Cargo.toml && echo "rust, obviously"
rust, obviously
❯ printf "%s\n" alpha beta gamma | grep beta
beta
❯ cd "C:\Program Files"
C:\Program Files
What Niubash is
- Bash syntax.
if,for,case,$(...), pipes, redirects, heredocs, functions, aliases — the whole grammar, powered by rubash, which is gated on the GNU Bash project's own 83-suite upstream test corpus (83 of 83 suites pass, per the 2026-10-12 full re-run: 62 byte-identical on Windows, 20 differing only on environment-bound lines, and the one nameref residual proven to be GNU Bash's own coproc reap-timing race — see the rubash compatibility ledger). - Windows-native. One binary, one process. Native Windows paths
(
C:\...andC:/...), direct execution ofgit.exe,node.exe,cargo.exe,python.exe— no VM, no emulation layer. The Windows-native path is the shell's first-class representation, POSIX- and WSL-style spellings are understood on input, and the Rubash executor translates POSIX-form arguments deterministically before a native child starts:/d/repoarrives atpython.exeasD:\repo, while shapes the executor does not classify as paths (/nonexistentand/fn main) arrive byte for byte. The native command processor keeps its/C-style switch-position operands verbatim. The full contract — the exact rules, thecmd.execarve-out, and the__RUBASH_ARGV_DIALECT=legacypass-through switch — is stated in the Windows Path Contract. - Unix commands included. WinuxCmd ships
ls,cat,grep,find,test,printf, and friends as Windows command links, with no separate installation. - AI-native.
niu -cis a contract: no banners, stable stdout/stderr, exact exit-code propagation. What an agent writes is what the process receives — the quoting roulette of PowerShell and the path mangling of MSYS/Git Bash are both gone. - A prompt you'll enjoy. The real theme ecosystems — oh-my-bash's and bash-it's catalogs (agnoster, spaceship, pure, the p10 family, ...) — plus a git prompt that grows teeth inside any repository, syntax highlighting, autosuggestions, vi and emacs modes, and Ctrl+R history search.
- The bash ecosystem as the plugin system. oh-my-bash, bash-it,
bash-completion and any git source install through
niu plugin— nothing is sourced until you enable it. A ~540-row recipe index (niu plugin recipe list) covers themes, plugins, aliases, completions and prompt tools.
The documentation
| Guide | What it covers |
|---|---|
| Getting Started | Zero to a git prompt in ten minutes |
| Advanced Usage | Execution modes, startup files, themes, plugins, completion, debugging |
| Install & Self-Update | Installer, portable zip, Windows Terminal profile, updates |
| Bash Compatibility Matrix | What Bash surface is verified, layer by layer |
| Performance | Every number pinned to the issue or PR that measured it |
| Built-ins & Fast Paths | All 64 built-ins, fast-path fallbacks, WinuxCmd overlap |
| Architecture | rubash + WinuxCmd + ruline, path model, host contract |
| Windows Path Contract | logical root, dispatcher selection, and layer ownership |
| Roadmap | What is done, what is next |
Get it
Download the installer from
GitHub Releases, install it
with winget (winget install --id Unixwin.Niubash), install it with Scoop
(see Installer and Self-Update), or build
from source:
git clone https://github.com/unixwin/niubash.git
cd niubash
cargo build --release
target\release\niu.exe
Keep it current with niu --self-update (or self-update inside the
shell) and wpm update winuxcmd for the Unix command set. Questions and bug
reports go to
github.com/unixwin/niubash/issues.
Shell semantics live upstream in rubash — fix the engine, and every Bash user on Windows wins.
Why Niubash
The long version of the pitch. The README sells it in five seconds; this page shows the receipts.
The Windows shell civil war
Every Windows developer knows the tabs open on their machine:
| Option | The fine print |
|---|---|
| CMD | Frozen in 1987. Your company's docs still paste it. |
| PowerShell | A genuinely powerful automation language. It is not Bash — your for loops, grep, and quoting instincts die on arrival. |
| WSL | A whole Linux distribution as a hobby you didn't sign up for. Boot a VM to print a directory. Dock your Docker Desktop's memory. Greet /mnt/c/Users/you/.... |
| Git Bash / MSYS2 | Brilliant emulation with a cost: it translates, mangles, and converts your paths at the worst possible moments, and every git pays an emulation tax. |
The treaty
Niubash is one native Windows binary that runs Bash syntax on Windows paths
with real Windows programs — and brings the Unix commands Windows never had
(ls, cat, grep, find, test, printf, ...).
| Niubash | WSL | Git Bash | PowerShell | |
|---|---|---|---|---|
| Bash syntax | ✅ | ✅ | ✅ | ❌ |
Native Windows paths (C:\..., no /mnt/c) | ✅ | ❌ | ⚠️ conversion quirks | ✅ |
Calls git.exe / node.exe directly | ✅ | ⚠️ via /mnt/c | ⚠️ path translation | ✅ |
Unix commands (ls, grep, find) | ✅ | ✅ | ✅ | ❌ |
| Cold start to prompt | ~170 ms | seconds | ~1 s | ~280 ms |
| No extra OS, no VM | ✅ | ❌ | ✅ | ✅ |
| Themes, git prompt, plugins | ✅ | — | ✅ | ⚠️ |
One binary. One process. No distro to patch, no emulation layer to appease.
PowerShell eats arguments
Windows itself is the root cause: the platform has no argv array. Every executable receives a single command-line string and parses it with its own rules — and PowerShell adds a second parser on top. That's how PowerShell/PowerShell#1995 ("Arguments for external executables aren't correctly escaped") became a household name, and how dotnet/runtime#23347 opens by citing "the ongoing quoting woes PowerShell experiences."
Same command line, two shells. Watch what actually reaches the process:
# PowerShell 5.1 # Niubash
> node -e "console.log(JSON.stringify( ❯ node -e "console.log(JSON.stringify(
process.argv.slice(1)))" "a b" "" "c\"d" process.argv.slice(1)))" "a b" "" "c\"d"
"e\f" "---" "e\f" "---"
ParserError: TerminatorExpectedAtEndOfString ["a b","","c\"d","e\\f","---"]
That command is written the way any model trained on Bash would write it. PowerShell throws a parse error before the process even starts. And when you quote it PowerShell's own way, the damage is quieter but still real: five arguments in, two mangled ones out — the empty string vanishes, the embedded quote is flattened, the last two arguments fuse into one:
> node -e "console.log(JSON.stringify(process.argv.slice(1)))" "a b" "" 'c"d' "e\f" "---"
["a b","cd e\\f ---"]
Agent casualties, with receipts
For humans this is a nuisance. For AI agents it's a minefield: models are trained on Bash, their quoting instincts are Bash-shaped, and on a PowerShell machine every generated command is a roll of the dice.
- anthropics/claude-code#65162 — agent used a PowerShell here-string (
@'...'@) inside the Bash tool; the git commit message was silently corrupted, andgit commitstill exited 0. - anthropics/claude-code#83243 — trivial commands fail with
unexpected EOFon Windows when PowerShell is the primary shell. - anthropics/claude-code#76490 — Bash allow-list rules never match Windows drive-letter paths; every run re-prompts.
- openai/codex#31548 — Windows users are voting to make the Codex agent shell configurable; it is locked to PowerShell today.
- openai/codex#35995 — Python works in the interactive shell but silently disappears inside Codex task execution.
- openai/codex#33891 / openai/codex#36560 — the ChatGPT desktop app flashes PowerShell windows while its agent works.
- microsoft/vscode-python-debugger#233 — a space in a path yields incorrectly quoted debug commands.
The path philosophy: native in, native out
If your mental model says every Unix-flavored shell on Windows must contain a path-translation layer — because every one you've met so far did — that is the model running on precedent, not a fact about this product. In niubash, the Windows-native path is the first-class citizen: not the target of a conversion, but the representation the shell actually thinks in.
Windows-native binaries don't speak the MSYS dialect. Here is Git Bash, in the wild, failing at exactly the things Niubash does without thinking:
What just happened, command by command:
| Command | In Git Bash (MSYS) | In Niubash |
|---|---|---|
node -e "..." "C:\Users\you\repo" | the backslashes are eaten — the argument vanishes | argument arrives byte-for-byte |
cmd /c dir /c/Windows/... | cmd.exe rejects the MSYS path (exit 1) | native path, native tools, no guessing |
git grep "/fn main" | MSYS rewrites /fn into a Windows path — the pattern silently dies | / is just a character, not a path to convert |
The escape hatches are the confession
MSYS "solves" paths by guessing: it heuristically rewrites /c/foo into
C:\foo, and famously mangles innocent arguments along the way — the
notorious case of git grep "/pattern" silently becoming
git grep "C:\...\pattern". A heuristic that always guesses right does not
exist, which is precisely why Git for Windows ships MSYS_NO_PATHCONV and
MSYS2 ships MSYS2_ARG_CONV_EXCL: an off switch for path conversion is a
documented admission that the conversion layer breaks real commands. Under
MSYS, every native tool call is a game of path roulette, and the house
provides the abort switch next to the wheel.
Niubash keeps the boundary but changes its shape. The translation is
deterministic and lives in niu's own Rubash executor, not in an emulator
rewriting arguments behind the child's back: /d/repo reaches a native
child as D:\repo, /nonexistent and /fn main pass through byte for
byte, and the mapping does not check whether the path exists. The same
principle holds for the rest of the path surface: the Windows-native path
is not a format niubash converts into — it is the shell's internal
representation. POSIX-style (/c/..., /usr/bin),
WSL-style (/mnt/c/...), and Windows-style (C:\...) are input spellings
that all resolve to that one native reality:
❯ cd /c/Users/you/repo # MSYS-style input: understood
C:/Users/you/repo # output: always Windows-native
❯ node -e "console.log(process.cwd())"
C:\Users\you\repo # native binaries get native cwd
❯ cd "C:\Program Files" # Windows-style input: understood
❯ pwd
C:/Program Files
Input in any dialect. Output always native. One representation, zero
guessing: the executor's POSIX→native argument mapping is fixed and
documented (windows-path-contract.md), and the
one switch is __RUBASH_ARGV_DIALECT=legacy, which hands argv to the
child unwritten — a dialect selector for a documented mapping, not the
abort switch of a heuristic that might guess wrong. That is the honest
version for your fingers, and for your agent.
The verdict
Every incumbent made a bet with the tools of its decade: CMD froze,
PowerShell bet on a brand-new language, WSL bet on virtualization, and
MSYS2/Cygwin bet on emulation. For the actual problem — running Bash on
Windows, next to native Windows programs — three of those bets pay out
nothing, and the fourth is structurally guaranteed to leak: translating
between two path worlds is a guessing game, and guesswork embedded in
infrastructure surfaces at the worst possible moment. The escape hatches
(MSYS_NO_PATHCONV, MSYS2_ARG_CONV_EXCL) are the incumbents' own
documentation of that fact.
The correct architecture is not a better emulator. It is no emulator: a native implementation where the Windows path is the only representation that exists, where Bash is implemented as a language — and proven against GNU Bash's own 83-suite upstream test corpus (83/83 suites pass on the 2026-10-12 full ledger re-run: 62 byte-identical on Windows, 20 environment-attributed, and the single nameref residual proven to be GNU Bash's own coproc race — see the rubash compatibility ledger) — and where native programs are called as what they are: native. That is what niubash ships, and it is why the emulation stack's failure modes are not "reduced" here. They are categorically absent.
Emulation was the previous century's approximation of this architecture. Niubash is the architecture.
Coding agents on Windows, and the shell they run
Your agent does not run commands in your shell. It picks one, and on Windows that pick is made by a probe you can usually influence. This page lists the mechanisms, the agent-by-agent behaviour, and what niu has to provide.
The roster below tracks the agent directory on
unixwin.dev: 24 agents in five groups —
ready (terminal-native), the VS Code family, partial, blocked, and
not-yet-verified. The original machine verification was done on 2026-10-16
(niu 1.4.0, niu-git 2.55.0.5 flat layout, Git for Windows 2.50.1 at D:\Git,
a WSL2 distro installed; opencode, codex (forked), ZCode). Entries added in
the 2026-10-21 expansion are marked source-verified when the claim comes
from reading shipped code rather than a live run; entries from upstream issue
threads are marked as reported. Behaviour statements track the current
release, v1.5.0.
--ec — the verbatim handoff cookbook
When a host cannot guarantee byte-exact quoting — or the command travels
through several shells on its way to this one — stop quoting altogether:
encode the command as base64 and hand niu the payload. It arrives as one
argv word no transport layer can rewrite; niu decodes it and runs it through
the regular -c route. Leading shell flags (-e -u -o pipefail --norc)
apply exactly as with -c, words after the payload are $0 plus positional
parameters, and the exit code and GNU error surface are the unencoded ones.
| Host | Encode + invoke |
|---|---|
| bash / WSL | niu --ec "$(printf '%s' "$cmd" | base64 -w0)" |
| PowerShell | niu -EncodedCommand [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($cmd)) |
| Python | subprocess.run(["niu", "--ec", base64.b64encode(cmd.encode()).decode()], ...) |
| Node | child_process.execFile("niu", ["--ec", Buffer.from(cmd).toString("base64")], ...) |
| Rust | Command::new("niu").arg("--ec").arg(B64.encode(cmd.as_bytes())) — the base64 crate, B64 being its general_purpose::STANDARD engine (imports in the snippet below) |
The spawn-site change: -c → --ec
Tools that shell out to niu make one change where the command line is built —
wherever the code assembles ["-c", cmd], it assembles ["--ec", b64]
instead:
#![allow(unused)] fn main() { use base64::engine::general_purpose::STANDARD as B64; use base64::Engine as _; // before — the command travels as raw argv; any layer that re-quotes, // expands, or truncates it breaks the call c.args(["-c", command]); // after — base64 in, the command bytes reach niu verbatim c.args(["--ec", &B64.encode(command.as_bytes())]); }
The swap is the same shape in every host language — a Python subprocess arg
list, a Node execFile argv array, a Go exec.Command, all take the encoded
payload as one more argument. Launcher flags keep working in front of the
payload: niu -eu -o pipefail --ec <b64> runs the decoded command under
errexit and pipefail, and words after the payload stay $0 plus
positional parameters.
Decoder tolerance is built for LLM-shaped payloads: an optional v1: prefix
(guards against MSYS-family path rewriting in transit), ASCII whitespace and
wrapped lines ignored, missing = padding accepted. The payload encoding is
UTF-8. PowerShell's own -EncodedCommand uses UTF-16LE, so a payload
produced for PowerShell must be re-encoded for niu — a UTF-16 payload fails
loudly (payload is not valid UTF-8), never silently. Windows caps one
command line at ~32 K chars (~24 K of script after base64 inflation); for
larger payloads write a temp script file and execute it.
Failure modes this removes at the transport level: nested-quote re-escaping
per host layer, $/backtick expansion by the calling shell, heredoc
corruption, \\ collapse across cmd→wsl→ssh, and CRLF translation of
inline scripts.
The one thing that usually just works
Launch the agent from a niu session:
niu
$ opencode # or codex, or any CLI agent
niu exports SHELL=<path to niu.exe>. Agents that follow the POSIX convention
read $SHELL and use it. That is how the agent driving this document runs: its
process tree is powershell.exe <- niu.exe <- opencode.exe, and opencode's
shell selector is literally
function o$(e, r) { return Xc(process.env.SHELL, void 0, r, e) ?? n$(e); }
// ^ which("bash") ?? "/bin/sh"
opencode has no niu-specific code at all (zero occurrences of niu in the
binary) and no config field for the shell; $SHELL is the whole mechanism.
The catch: $SHELL is not persisted by anything. It exists only in
processes descended from a niu session. Start the agent from the Start menu or
Explorer instead and $SHELL is empty, so the same agent falls through to
which("bash"), which on a machine with WSL resolves to
C:\Windows\System32\bash.exe and runs your commands in Linux.
The four mechanisms
| # | Mechanism | Reads | Covered by launching from niu |
|---|---|---|---|
| 1 | $SHELL (POSIX convention) | the environment | yes |
| 2 | Explicit per-agent setting | config file / CLI flag | n/a, set it once |
| 3 | Git for Windows probe | hardcoded paths, or derived from git | no |
| 4 | Bare name, a table, or PowerShell by default | PATH, ComSpec, PATHEXT | partly |
Mechanism 3's hardcoded C:\Program Files\Git candidates are deliberately
not claimed by the niubash installer (the niubash#398 ruling: a per-user
install never writes an admin-walled foreign directory — see
the installer contract).
What hits niu today is the probe's second arm — the bash.exe derived from
the git found on PATH — plus explicit settings (mechanism 2). But the
second arm lands on niu only when Git for Windows is absent: with it
installed, probe (1)'s hardcoded directories win and the git on PATH
is never consulted (niubash#1031). Mechanism 4
is why a bare bash cannot be redirected from the user PATH alone.
What winuxcmd\bin\bash.exe actually is
Since niubash#377 it is niu itself under another name: the installer runs
niu --relink-shells, which links bash.exe/sh.exe as hardlinks to
niu.exe wherever the filesystem allows, and the engine takes the face from
argv[0] ($0, BASH_VERSION, POSIX mode for sh). No extra process, no
launcher hop — the ~13 ms per--c tax a forwarding launcher costs
(niubash#377) exists only on filesystems without hardlinks, where the
fallback is a forwarding shim that sets NIU_INVOKED_AS and re-execs niu
with argv preserved.
The other historical wart is also closed: a console-less parent used to get a
visible console window per command through the launcher chain
(niubash#379 — Claude Code flashed a window for every command). The fix
family shipped in v1.4.2: CREATE_NO_WINDOW on redirected spawns
(rubash#668, rubash#909), the winuxcmd-shim launcher suppressing orphan
consoles (WinuxCmd#1282), and one hidden console per niu session instead of
one per child (niubash#462 — see Performance).
Which shell is my agent actually using?
Ask the agent to run this and compare the signatures:
echo "SHELL=$SHELL"; uname -s; uname -a
| What you see | Shell | Notes |
|---|---|---|
uname -s = MSYS_NT-..., uname -a ends x86_64 Msys | niu (winuxcmd shim) | what you want; $SHELL points at niu.exe |
uname -s = MINGW64_NT-..., MSYSTEM=MINGW64 | Git Bash | Git for Windows' own runtime |
uname -s = Linux | WSL | the surprising one; the agent reached System32\bash.exe |
uname not found, $SHELL empty | PowerShell or cmd | check $PSVersionTable.PSVersion vs %COMSPEC% |
The same check appears in Cursor's own support threads, where the fix is
verified by uname -a ending in MINGW64_NT-... instead of
microsoft-standard-WSL2.
Interpreting the result:
Linuxmeans the agent fell through towhich("bash"). Fix the mechanism that agent uses, below.MINGW64_NTmeans it found Git Bash. If you want niu instead, set the agent's explicit shell (mechanism 2) or the$SHELLvariable.- Empty
$SHELLwith PowerShell means the agent defaults to PowerShell, which is safe but not bash-compatible.
Agent reference
| Agent | Status | Mechanism | |
|---|---|---|---|
| opencode | ✅ ready | $SHELL | |
| Claude Code | ✅ ready | git-derived probe / CLAUDE_CODE_GIT_BASH_PATH | |
| Codex (unixwin fork) | ✅ ready | native ShellType::Niu detection | |
| Zed | ✅ ready | terminal.shell.program | |
| Goose | ✅ ready | GOOSE_SHELL | |
| DSH (DeepSeek Harness) | ✅ ready | plugin profile | |
| VS Code (Copilot agent) | ✅ ready | VS Code family probe / automationProfile | |
| Windsurf | ✅ ready | VS Code family probe | |
| Trae | ✅ ready | VS Code family probe | |
| Kiro | ✅ ready | VS Code family probe (inferred) | |
| ZCode | ✅ ready | VS Code family probe (verified) | |
| Cline | ✅ ready | editor terminal / automationProfile | |
| Roo Code | ✅ ready | editor terminal / automationProfile | |
| Kilo Code | ✅ ready | editor terminal / automationProfile | |
| Continue | ✅ ready | editor terminal / automationProfile | |
| Cursor | ⚠️ partial | IDE workaround exists; Agent CLI hardcodes PowerShell | |
| Devin | ⚠️ partial | no native integration; TUI blocked by niubash#455 | |
| Qwen Code | ⚠️ partial | MSYSTEM/TERM sniff → Git Bash lookup | |
| Gemini CLI | ❌ blocked | unconditional PowerShell | |
| Aider | ❌ blocked | no shell option | |
| Amazon Q Developer CLI | ❔ unverified | — | |
| Amp | ❔ unverified | — | |
| OpenHands | ❔ unverified | — | |
| Junie (JetBrains) | ❔ unverified | — |
Works out of the box — terminal-native agents
opencode
- Mechanism:
$SHELLfirst, thenwhich("bash"), then/bin/sh. Itsgitbashmode is implemented as "use$SHELL". No config field; the V2 CLI settings and core config have no shell key. - Set it to niu: launch from niu, or persist
SHELLto the user environment ([Environment]::SetEnvironmentVariable('SHELL', "$env:LOCALAPPDATA\Programs\Niubash\niu.exe", 'User')in PowerShell) to cover every launch path. Nothing else is read. - Failure mode: falls to
which("bash")->System32\bash.exe-> Linux. - Separate code path: the self-updater resolves
git --exec-pathup three levels plusbin\bash.exeand refuses to update with "Git Bash is required to update OpenCode" when that file is missing. It does not consult$SHELL. The niu-git package manifest places...\winuxcmd\opt\niugit\bin\{bash,sh}.exeso the probe resolves and awpmrefresh keeps it. See niubash#376. - Source: shipped binary, read locally.
Claude Code
- Mechanism: vendor docs. Without
CLAUDE_CODE_GIT_BASH_PATHit looks forbash.exein (1)C:\Program Files\GitandC:\Program Files (x86)\Git, then (2) thegitonPATH, usingbin\bash.exefrom that installation. It skips agitsitting in the launch directory or below it, or undernode_modules/.venv/env. - Set it to niu: probe (1)'s hardcoded directories are deliberately left
unclaimed by the installer (the niubash#398 ruling — see below), so on a
machine without Git for Windows it is probe (2) that lands on niu: the
gitonPATHresolves intowinuxcmd\bin, whosebash.exeis the niu face described above. With Git for Windows installed, probe (1) wins and only the explicit variable gets niu — setCLAUDE_CODE_GIT_BASH_PATHinsettings.jsonto...\winuxcmd\bin\bash.exe. - Trap: the variable only accepts a file named
bash.exe,sh.exe,bashorsh. Point it atgit-bash.exeand it is ignored with a warning. Pointing it atniu.exeis likewise ignored — but the hardlinkedbash.exeisniu.exeunder an accepted name, so the accepted-name requirement costs nothing now that niubash#377 landed theargv[0]dispatch. Worse, a value that names no file at all is ignored silently (no warning): the host falls back to probe (1) and runs Git Bash. An unrendered template token from a config generator (e.g.@@windows.home@@\...) is exactly such a value (niubash#1031). - Check which shell the host actually runs:
niu doctorhas aclaude code shellrow (Windows only, shown when~/.claudeexists) that names the fallback and the exact path to set. In-session,uname -sreportsMSYS_NT/MINGW64_NTunder Git Bash and niu's own signature under niu — if the skill's commands assume niu anduname -ssays otherwise, report the host setting instead of working around it. - History: this configuration is the one that exposed niubash#379 (a visible console window per command through the forwarding launcher). Fixed in rubash#668 and shipped in v1.4.2 — if you still see the flash, upgrade.
- Failure mode: since v2.1.120, absent Git Bash means PowerShell, not Linux.
- Source: vendor documentation.
Codex
- Mechanism: a shell table with per-shell candidate paths. Windows entries
include
bash -> /bin/bash,sh -> /bin/sh,pwsh,powershell,cmd. - Set it to niu: the unixwin-maintained fork adds
ShellType::NiuwithC:\Program Files\Niubash\niu.exe,C:\Program Files (x86)\Niubash\niu.exe,%LOCALAPPDATA%\Programs\Niubash\niu.exeand aniulookup onPATH; the exec policy also whitelistsniu.exe -C,-c,-lc,--repl-command. Zero configuration: install the fork and niubash and it is selected. This is the shape the other agents need. - Source:
codex-rs/shell-command/src/shell_detect.rs, read locally.
Zed
- Mechanism: explicit.
terminal.shell.programnames the shell, and the agent uses that terminal. - Set it to niu: point
terminal.shell.programatniu.exe. - Source: settings in use on this machine.
Goose
- Mechanism:
GOOSE_SHELL. On Windows the shell tool readsGOOSE_SHELL, defaults tocmd, and dispatches argument style by file name:pwsh/powershellget-Command,cmdgets/C, and every other name gets-c— which is exactly niu's one-shot syntax. - Set it to niu: persist
GOOSE_SHELLto the niu path (same[Environment]::SetEnvironmentVariablepattern as$SHELLabove), open a new terminal, rungoose, and have it execute any command — the output is bash dialect, not cmd. - Source: source-verified (2026-10-21 HEAD):
block/goosecrates/goose/src/agents/platform_extensions/developer/shell.rs,windows_shell()and the argument dispatch. Not yet run per-machine; the desktop app has separate login-shell logic (ui/desktop loginShellPath) — the CLI behaviour is what counts here.
DSH (DeepSeek Harness)
- Mechanism: plugins.
dsh-niuships a profile bundle that enablesniu-sandboxandtool-bash, disables the PowerShell shell/tool rows, and adds a settings card. A third party shipsdsh-niubash-onlyin the same spirit. - Set it to niu:
dsh plugin --profile web add @cmx666/dsh-niu-bundle@<version>. - Source: the plugin READMEs.
The VS Code family
Cursor aside, the VS Code family is one shared probe:
var HX = ["C:\\Program Files\\Git\\bin\\bash.exe",
"C:\\Program Files (x86)\\Git\\bin\\bash.exe"];
// then: which("git") -> dirname(git) + "/../bin/bash.exe" and "/../../bin/bash.exe"
- Applies to: VS Code (Copilot agent), Windsurf, Trae, Kiro, ZCode, and extensions that use the editor's terminal or automation profile (Cline, Roo Code, Kilo Code, Continue). Cursor is VS Code lineage too, but both of its products route around this probe — it gets its own entry under partial.
- Set it to niu: the hardcoded candidates stay unclaimed (the #398 ruling
again), so today the
which("git")arm is the one that lands on niu'swinuxcmd\bin\bash.exe— fix the entry directory once and the whole family follows. For explicit control, point the automation profile at niu:terminal.integrated.automationProfile.windows={"path": "<niubash>\\niu.exe", "args": []}. Agents that shell out through the automation profile inherit it. - Failure mode: PowerShell, or cmd if neither is configured.
- Source: the probe sequence above was read out of ZCode's
app.asarlocally — ZCode is the family's verified member; the rest share the lineage. Kiro is the one family entry the original probe list did not name — it is Code OSS lineage and is listed here on that basis; per-machine confirmation welcome.
The editor extensions
Cline, Roo Code, Kilo Code and Continue do not pick a shell at all: commands
run through the host editor's terminal or automation profile, so they inherit
whatever the family probe resolved. Set the host editor's
automationProfile (or leave the git-derived arm to find niu) and every
extension follows.
Partial — a workaround exists
Cursor
Two products, both currently unhelpful:
- IDE agent: ignores
terminal.integrated.defaultProfile.windowsandterminal.integrated.automationProfile.windowsand runs PowerShell; the workaround is enabling the Legacy Terminal Tool setting. Some versions pick WSL bash instead, which is why their threads recommend nulling the PowerShell and WSL profiles withterminal.integrated.useWslProfiles: false. - Agent CLI: hardcoded to PowerShell. No
--shellflag, no shell field in~/.cursor/cli-config.json, and$SHELL/$COMSPECignored. The shippeddetectShellType()putsisWindows && (commandExists("pwsh") || commandExists("powershell"))in the same||chain as the string match, so on Windows the PowerShell arm fires regardless of the hint and every later branch is unreachable. A workingNaiveTerminalExecutorexists but nothing routes to it. - Set it to niu: not possible today through configuration. Reported upstream; nothing to do on the niu side until they expose a shell path.
- Source: upstream issue threads quoting the shipped detection code.
Devin
- Mechanism: none — there is no niubash native integration (no
ShellType::Niu-style detection, no plugin profile, no install hook). It launches fine from a niu session, but its shell selection is unverified. - Known blocker: niubash#455 (open).
devin.exev3000.11.92 drives its interactive TUI through the legacy Win32 console API (ReadConsoleInputW/SetConsoleCursorPosition) when stdout is a real console — under niu that path currently renders a white screen and dead keys. With stdout a pipe it takes an ANSI fallback path that works. Two upstream-side bugs ride along: the install script'scurl|bashrunsdevin setupunconditionally with no tty check, andsetupdoes not exit on stdin EOF. rubash#913 fixed the spawn-side half (one hidden console per session); the TUI console channel is the remaining work — watch the issue. - Workaround today: run
devin setuponce in a normal terminal (PowerShell / Windows Terminal) to complete login, then drivedevinfrom a niu session for non-TUI work. - Source: niubash#455 investigation (2026-10-21); no per-machine shell verification. "Not verified here" alumni — promoted out of the list with findings, not with a working setup.
Qwen Code
- Mechanism: since forking gemini-cli (v0.8.2, per its README
acknowledgement) it has carried its own detection — different from the
parent's unconditional PowerShell:
MSYSTEMstartingMINGW/MSYS, orTERMcontainingmsys/cygwin, routes tofindGitBashPath(), which scansPATHforbash.exeand then checks the two hardcodedC:\Program Files[ (x86)]\Git\bin\bash.execandidates. Otherwise it falls back toComSpec(cmd/PowerShell). - Set it to niu:
MSYSTEMis empty in a niu session and setting it is a documented experiment (see Known traps). WithMSYSTEM=MINGW64persisted to the user environment, thePATHarm offindGitBashPath()hitswinuxcmd\bin\bash.exe— the niu face — before ever reaching the unclaimed Program Files candidates. - Source: source-verified (2026-10-21 HEAD):
QwenLM/qwen-codepackages/core/src/utils/shell-utils.ts(getShellConfiguration()/findGitBashPath()). Read-code conclusion, not yet run per-machine; a successful live run promotes this to ready.
Blocked — no supported path today
Gemini CLI
- Mechanism:
getShellConfiguration()returns PowerShell unconditionally on Windows.ComSpecis only consulted to decide betweenpwshandpowershell.exe; there is no bash branch. - Set it to niu: not possible in released code. Two upstream proposals
exist: detect MSYS via
process.env['MSYSTEM']and route tobash -c(issue #26567), and prefer Git Bash by searchingPATHfor abash.exewhose path containsgit(PR #18367). Its fork Qwen Code already implemented the first idea — see that entry. - Failure mode: PowerShell, and on locked-down machines an execution-policy error that stops the agent entirely.
- Source: upstream source and issue threads.
Aider
- Mechanism: there is no shell selection option.
/runuses PowerShell orcmd.exeon Windows, and the model-visible environment reportsShell: COMSPEC=....--suggest-shell-commandsand--shell-completionsare unrelated. - Set it to niu: not supported. Launching Aider from niu does not change
the shell it uses for
/run. - Failure mode: cmd/PowerShell command syntax, not a bash failure.
- Source: upstream options reference and changelog.
Not verified here
Amazon Q Developer CLI, Amp, OpenHands and Junie (JetBrains) have no entry
beyond the generic guidance: no per-machine run and no read selector yet.
OpenHands typically executes inside a container/sandbox, and Junie runs
inside JetBrains IDEs — whether the host terminal's shell configuration
reaches their command execution is exactly the open question (for Junie, a
first probe is pointing the IDE's built-in terminal at niu.exe and running
the verify command through it). The four-mechanism table and the verify
command above are the self-serve route; field reports welcome.
What niu provides, and what is still open
| Path | Serves | Status |
|---|---|---|
SHELL exported to session children | mechanism 1, for agents launched from niu | ✅ works today |
SHELL persisted to the user environment | mechanism 1 for every launch path | ⬜ open — one HKCU\Environment value; the installer does not write it yet |
<root>\bin\{bash,sh}.exe, <root>\winuxcmd\bin\{bash,sh}.exe | mechanism 4 bare-name users, the git-derived probes | ✅ hardlinked argv[0] faces via niu --relink-shells (installer's [Run]), forwarding-shim fallback off NTFS |
...\winuxcmd\opt\niugit\bin\{bash,sh}.exe | opencode's updater probe (git --exec-path up three) | ✅ placed by the niu-git package manifest, kept by wpm refresh |
C:\Program Files[ (x86)]\Git\bin\{bash,sh}.exe | mechanism 3 probe 1 (Claude Code, VS Code family) | ❌ deliberately unclaimed — niubash#398 ruling, tested invariant; revisit needs an accepted opt-in elevated task |
The entry directory ...\winuxcmd\bin must contain only names you intend to
own globally (git, sh, bash), because it is what goes on PATH.
Why PATH cannot win against System32
Windows resolves a bare name handed to CreateProcess by searching the
application directory, the current directory, the system directory, the
Windows directory, then PATH. Measured with the entry directory first on
PATH:
| Caller | bash becomes |
|---|---|
cmd /c bash -c 'uname -s' | winuxcmd's bash (MSYS_NT-...) |
PowerShell & bash | winuxcmd's bash |
Python subprocess(['bash', ...]) | WSL (Linux) |
Shells resolve names themselves, so PATH order decides for them. A process
that passes the bare name to CreateProcess never sees PATH before the system
directory, so a bare bash cannot be fully taken over from a per-user PATH.
Since the C:\Program Files\Git convention slot is deliberately unclaimed,
the remaining complete answer is telling callers to use sh, which has no
System32 counterpart.
Recommended order of work
- Installer writes
SHELLto the user environment, and removes it on uninstall. One registry value, no elevation, and it covers the largest class of agents including every POSIX-flavoured CLI. Users who launch from niu already have it; this makes it independent of the launch method. niu setup agents(idempotent) creates the non-elevated paths, prints what each probe resolves to, and says which entries need elevation.- An accepted, opt-in elevated task is the only way the
Program Files\Gitcandidates could ever be claimed — per the #398 ruling it takes evidence that an editor resolves that exact path (Claude Code and the VS Code family probe are that evidence) plus explicit user opt-in. - Per-agent settings for the agents that read neither
$SHELLnor the Git probes: Zed, DSH (done), the Codex fork (done), the VS Code automation profile.
Two things not to do: do not add winuxcmd\usr\bin to PATH (hundreds of
names, including ones System32 owns), and do not replace
C:\Windows\System32\bash.exe.
Known traps
MSYSTEMis empty in a niu session. Tools that sniff MSYS through it (Qwen Code's shipped detection, Gemini CLI's proposed fix) will not see niu by default. Setting it is untested and changes how other MSYS-aware tools behave, so treat it as an experiment.unamein the winuxcmd shim reportsMSYS_NT-.... Anything that branches onunamewill classify the host as MSYS, which is deliberate for compatibility but visible to autotools and similar.- Claude Code accepts only
bash.exe/sh.exe/bash/shinCLAUDE_CODE_GIT_BASH_PATH. - A
bashthat resolves to Windows' WSL launcher starts Linux bash, and there is no error: the agent simply runs your commands on another OS.
Getting Started with Niubash
A short walkthrough from zero to a working prompt with git status.
1. Build or download
git clone https://github.com/unixwin/niubash.git
cd niubash
cargo build --release
After building, the binary is at target\release\niu.exe. You can run it
directly, or add target\release to your user PATH using your normal Windows
environment settings:
target/release/niu.exe
If you are using the release zip, niubash automatically runs the activation script on first start when command links are missing:
niu winuxcmd/activate-winuxcmd.sh
That creates local command links inside winuxcmd/, so ls, cat, and
friends resolve normally. Once the links exist, startup skips activation.
2. Start the shell
niubash
You should see something like:
user@DESKTOP ~
$
Type exit or press Ctrl+D to quit.
3. See the git prompt
cd into any git repository:
cd C:\Users\you\repo
# inside a repo, the first prompt row gains a branch segment:
user@DESKTOP ~/repo (main)
$
The segment is deliberately small — the Git Bash shape, not a status dashboard:
| Shape | Meaning |
|---|---|
(main) | on branch main, working tree clean |
(main*) | on branch main, working tree dirty — the trailing * is the only dirty marker: any staged, unstaged, or untracked change sets it, and there are no per-category counts |
(a1b2c3d) | detached HEAD — the short commit SHA instead of a branch name |
| (no segment) | outside a repository (or git unavailable) — the segment is simply absent |
The branch segment is always cyan; clean versus dirty is told by the *,
not by a colour change. A fresh git init repository shows its unborn
branch name too.
4. Try some commands
pwd # prints C:/Users/you/repo
ls -la # Unix-style listing
echo "hello from $USER"
for i in 1 2 3; do echo $i; done
if [ -f Cargo.toml ]; then echo "yep"; fi
cat Cargo.toml | grep name
grep -n "fn main" src/main.rs
Windows paths work directly:
ls C:\Windows\System32\drivers\etc
ls D:/Projects
cd "C:\Program Files"
Multiline blocks work naturally:
for f in *.toml; do
echo "found $f"
done
5. Try git completions
git ad<Tab> # completes to `git add`
git commit -<Tab> # shows flags: --message, --all, --amend
git push --fo<Tab> # completes to --force
git branch -<Tab> # shows -d, -D, -m, -v, -a, -r
6. Set up your config
Create ~/.niubashrc for interactive shell code — environment, aliases,
functions — plus optional defaults and theme enablement:
# Optional floor knobs: they only shape the built-in default prompt and
# completion UI. An external theme claims PS1 and overrides the floor.
# NIU_PROMPT_CWD_STYLE='home' # home | full | basename
# NIU_COMPLETION_STYLE='column' # column (default) | gnu | ide | list | inline
if [ -z "${HOME:-}" ] && [ -n "${USERPROFILE:-}" ]; then
HOME="$USERPROFILE"
export HOME
fi
export EDITOR=vim
alias ll='ls -la'
alias la='ls -a'
alias gst='git status'
alias gco='git checkout'
alias gl='git log --oneline --graph --decorate --all'
hello() {
echo "hello from niubash"
}
~/.niubashrc is sourced only for the interactive REPL and the -C
one-shot REPL command path. It does not run for niu -c ..., script files,
or stdin script execution, so agent and CI surfaces stay deterministic.
On Windows, ~/.niubashrc is the only startup file niu reads on the
interactive face. --login/-l are accepted there but change nothing:
niu --login -i sources exactly what niu -i sources — the generated
plugin loader, then ~/.niubashrc (--rcfile and NIU_RC_POLICY apply
unchanged) — never the GNU profile chain. The login marker still matters
on two faces: a non-interactive niu -l -c ... sources the GNU profile
chain (/etc/profile, then the first of ~/.bash_profile →
~/.bash_login → ~/.profile), and POSIX mode (--posix, the sh/ash
faces) keeps that chain on every platform — a login POSIX shell reads the
profile chain whether interactive or not. On Linux/macOS, interactive
login shells additionally read the GNU profile chain before
~/.niubashrc, exactly as GNU bash does. Pre-rename
legacy rc files and ~/.bashrc are never sourced directly,
migrated, or modified — a session that finds no ~/.niubashrc simply starts
without one. Plugin enable/disable state, the source registry, and other
machine state live under ~/.niubash/ and are managed by niu plugin, not
by editing files.
6b. Prompts and themes
The built-in prompt is a floor, not an identity: it renders only while
nothing claims PS1. Anything that sets PS1 — your own line in
~/.niubashrc, an enabled oh-my-bash theme, or eval "$(starship init bash)"
— owns the prompt completely, and disabling it lets the built-in floor
render again.
The floor itself has one knob, NIU_PROMPT_CWD_STYLE (home by default;
also full or basename), set in ~/.niubashrc:
NIU_PROMPT_CWD_STYLE=full
Themes live in the external ecosystem (see the next section) — enable one
and its PS1 takes over the prompt; disable it and the floor comes back.
7. Plugins: the external ecosystem
Themes and plugins come from external plugin managers, installed and
enabled through niu plugin. The curated catalog has oh-my-bash,
bash-it, and bash-completion; any git URL, owner/repo shorthand, or
local path works too. Installing is not activating — nothing a source
ships runs until you enable it:
niu plugin add oh-my-bash # install from the catalog
niu plugin enable oh-my-bash # records the source in the manifest
niu plugin enable agnoster # a theme asset -> OSH_THEME in the loader
niu plugin disable oh-my-bash # manifest updated; the built-in floor returns
Since the niubash#359 rework (v1.4.2), plugin verbs never write your rc.
What enable/disable update is the manifest — ~/.niubash/plugins.json
plus ~/.niubash/sources/registry.json — and every mutating verb regenerates
~/.niubash/generated/plugins.niu, the derived activation plane the host
sources before ~/.niubashrc (so your own PS1/alias/function lines always
win). POSIX-mode interactive shells load it too — after the profile chain
and before $ENV for login shells, before $ENV otherwise
(niubash#603). A failed generation never replaces the last good loader, and
NIU_PLUGIN_LOADER=off disables loading entirely. If your rc still contains
legacy # >>> niu source <id> managed blocks, the loader stays off until
they are removed — niu plugin migrate-rc --diff shows exactly what to take
out; the removal is always your own edit. Use niu plugin list and
niu plugin discover for the current inventory and state.
Executable CLI tools (starship, fzf, eza, bat, fd, ripgrep, zoxide, dust,
duf, erdtree, direnv, niu-git …) install through your real package
managers — niu downloads nothing (download retraction, owner ruling
2026-10-04). niu plugin add fzf prints the commands:
niu plugin add fzf # prints: wpm install fzf (Windows, first choice),
# winget/scoop alternatives, apt/dnf/brew,
# plus the upstream release URL
Two systems coexist: the Unix command layer (ls, cat, grep, … plus
the application tools above) is owned by wpm on Windows (wpm install <tool>, wpm links rebuild, wpm update winuxcmd) — wpm is the
first-class tool channel there (owner correction 2026-10-03); on Linux and
macOS the native package managers (apt/dnf/yum/brew) own that plane.
niu plugin owns the bash-ecosystem extension plane (git sources, themes,
completions) on every platform.
What next
- Plugin System Direction for the v3 plugin model
- Plugin System Roadmap for the execution sequence
- Oh My Niubash Ecosystem for the external plugin ecosystem design
- Roadmap to see what is planned
- Source at github.com/unixwin/niubash
Advanced Niubash Usage
This guide covers the surfaces that matter after the first successful launch: execution modes, startup files, prompt/theme plugins, command discovery, and update/debug workflows.
For first-time setup, start with Getting Started.
Execution Modes
Niubash has three intentionally different execution paths:
niubash # interactive REPL
niu -c 'pwd; echo "$SHELL"' # quiet script/CI command mode
niu -C 'alias ll; pwd' # one-shot REPL command
- Use the interactive REPL for normal shell work.
- Use
-cfor scripts, tests, CI, and coding agents. It does not load~/.niubashrc, the generated plugin loader, prompt plugins, or interactive lifecycle hooks. - Use
-Conly when a one-shot command needs the same startup state as the interactive REPL. It loads~/.niubashrcand lifecycle hooks, then exits.
This separation keeps automation deterministic while still allowing a rich interactive shell.
Verbatim base64 handoff: --encoded-command
When the command text cannot survive another shell's quoting (an agent
handoff, a CI matrix, a PowerShell launcher), pass it base64-encoded. The
payload is decoded and run through the -c route, so leading flags keep
their meaning (-e -u -o pipefail --norc ...) and words after the payload
are $0 and positional parameters, exactly like -c:
niu --encoded-command 'cHdkOyBlY2hvIG9r'
niu --ec 'cHdkOyBlY2hvIG9r' # short alias, same route
niu -EncodedCommand 'cHdkOyBlY2hvIG9r' # PowerShell spelling
Three spellings work: --encoded-command, --ec, and -EncodedCommand
matched case-insensitively (niubash#474, #477). A lone -ec is not one of
them — with a single dash it stays GNU -e -c. An optional v1: prefix on
the payload guards against MSYS path rewriting on the way in. A missing
payload is an error, not an empty run.
One-shot init file: NIU_ENV / BASH_ENV
By default -c loads nothing — no rc, no plugins, no hooks. If your script,
CI job, or coding agent needs shell aliases, exported variables, or PATH
tweaks, point NIU_ENV (or bash-compatible BASH_ENV) at a dedicated init
file. Only that one file is sourced, so the interactive-only content in
~/.niubashrc stays out of the one-shot path.
# ~/.opencode.env — a minimal init file for agents
export PATH="$HOME/tools:$PATH"
alias ll='ls -la'
export DOCKER_CONTEXT=my-cluster
NIU_ENV=~/.opencode.env niu -c 'll | head'
# or bash-compatible:
BASH_ENV=~/.opencode.env niu -c 'echo "$DOCKER_CONTEXT"'
NIU_ENV takes precedence over BASH_ENV when both are set. A leading ~
expands to your home directory. If the file does not exist, it is silently
skipped and the command runs without it — the same behavior as GNU bash's
BASH_ENV.
With neither variable set, -c stays zero-load and fast.
Startup And Config
Use ~/.niubashrc as the normal human-authored entry point:
# Optional floor knobs — they only shape the built-in default prompt and
# completion UI; an enabled external theme claims PS1 and wins.
# NIU_PROMPT_CWD_STYLE='home'
# NIU_COMPLETION_STYLE='column' # column (default) | gnu | ide | list | inline
alias ll='ls -la'
export EDITOR=vim
# starship (or any tool that sets PS1) owns the prompt while it is active:
# eval "$(starship init bash)"
Themes and plugins are enabled through niu plugin. Plugin verbs never write
the rc (niubash#359, v1.4.2): they update the manifest
(~/.niubash/plugins.json + ~/.niubash/sources/registry.json) and
regenerate ~/.niubash/generated/plugins.niu, which the host sources
read-only before your rc — so rc lines always win
(see Plugin Workflow).
POSIX mode is no exception (niubash#603): the generated loader is niu's own
activation plane, not a user startup file, so interactive POSIX shells
(--posix, or invoked as sh) load it too. POSIX mode still governs the
user files exactly as GNU specifies — a login shell reads the profile
chain, an interactive shell reads $ENV instead of the rc — and the
loader takes the same relative seat it holds on the ordinary branch: a
login POSIX shell loads it after the profile chain and before $ENV; a
non-login POSIX shell loads it before $ENV. With $ENV in the rc's
seat, your $ENV lines win over the loader just as rc lines do.
Interactive shells read ONE startup file: ~/.niubashrc. By default it
is the only candidate: if it does not exist, the shell starts with no rc
at all — ~/.bashrc is not read. The single exception is opt-in: if you
explicitly picked the bashrc-fallback rc policy
(NIU_RC_POLICY=bashrc-fallback, or niu setup --rc-policy bashrc-fallback),
a genuinely absent ~/.niubashrc lets ~/.bashrc fill the slot instead
(the migration path for existing bash configurations). Either way the two never stack — one
config file, one blast radius, no implicit double-sourcing. Want the bash
layer under niu? Add one visible line to ~/.niubashrc:
[[ -f ~/.bashrc ]] && source ~/.bashrc
Explicit, visible, yours — the same shape as bash's own
.bash_profile → .bashrc chain. --norc skips startup files;
--rcfile <file> reads only the named file, exactly like GNU bash. The
pre-rename legacy rc names are never read, migrated, or
written. Machine state —
the plugin manifest and source registry, the generated
loader, test isolation, completion directories — is maintained by Niubash
itself and is not a user configuration entry point.
Script Debugging Flags
Niubash embeds the native script debugger: one debug session, two
frontends. --debug drives it from an interactive terminal and --dap
speaks the Debug Adapter Protocol for editors. Both imply extdebug
internally and never change your observable shopt extdebug setting.
--debug <script> — interactive debugger
niu --debug script.sh [args…] starts the session stopped at the entry
stop, before the first command runs. Commands are read from the controlling
terminal, never from the debuggee's stdin; the debuggee keeps its own stdio,
and the debugger prompt is (niu-dbg). The M1 command set includes
break/tbreak/enable/disable/delete, step/step+/step-/next/
finish, where/frame/up/down, list, print/eval, set var,
info locals|variables|args|functions|files|breakpoints, exceptions, and
continue/quit/kill.
Batch driving is the source <file> command inside the session, not a piped
debugger: when no terminal device opens and stdin is not itself a terminal,
the frontend refuses with a clear diagnostic and exit status 2.
--debug with -c, -s, or interactive -i keeps the legacy behavior:
it arms extdebug (DEBUG traps fire at every GNU stop site with
BASH_ARGC/BASH_ARGV populated) without opening the debugger frontend.
GNU bash accepts the same flag as a no-op, so scripts that pass --debug
keep running unchanged under GNU bash too.
--dap <script> — editor frontend
niu --dap script.sh [args…] serves DAP on stdio (Content-Length framed
JSON). niu --dap without a script is a pure server; the client's launch
request then names the program. niu --debug --dap script.sh is the
spelled-out editor launch form used by the bundled zero-JS VS Code
extension (editors/vscode/).
The adapter covers initialize, launch/attach (launch-equivalent),
setBreakpoints (line, function, conditional), setExceptionBreakpoints
(err-trap, set -e, parse-error), configurationDone, threads,
stackTrace, scopes, variables, setVariable, evaluate
(hover/watch/repl), next/stepIn/stepOut, continue, pause,
terminate, and disconnect, with initialized, stopped, terminated,
exited, output, thread, and breakpoint events.
--debugger — run bashdb (GNU parity)
niu --debugger script.sh mirrors GNU bash: the shell looks for the bashdb
starter file (bashdb-main.inc) and sources it before your script runs.
Search order: $BASHDB_START_FILE (set this when your bashdb lives under a
nonstandard prefix — Termux, a custom --prefix build), then
/usr/local/share/bashdb/bashdb-main.inc, then
/usr/share/bashdb/bashdb-main.inc. If no starter file exists, niubash
prints GNU's diagnostic pair (No such file or directory + warning: cannot start debugger; debugging mode disabled) and continues with
debugging disabled — exactly what GNU bash does. With bashdb installed,
existing bashdb users point the shell at their starter and upgrade in
place.
Do not put automation-critical behavior only in an interactive rc file. Pass
needed environment variables directly to niu -c or the script process, or
use NIU_ENV / BASH_ENV to source a dedicated one-shot init file (see
One-shot init file).
Completion
TAB completion has two independent axes: interaction (what TAB does to
the line) and presentation (how candidates are painted). The defaults are
select + column.
Interaction
NIU_COMPLETION_INTERACTION picks the TAB behavior:
select(default) — zsh menu-select. TAB #1 splices the first candidate into the line and highlights it; TAB/Shift-TAB cycle; Up/Down move one row; Left/Right move one column with zsh edge wrap; Enter accepts the pick and closes the menu (a second Enter runs it); Esc rolls back. A lone candidate completes outright, and bare TAB on a blank line completes the empty word exactly like any other word.insert— the two-step common-prefix contract: TAB #1 completes the common prefix and stops, TAB #2 opens the menu. Enter commits the highlighted candidate without running it; Esc keeps the inserted text.cycle— TAB #1 inserts the first candidate and opens the grid; further TAB/Shift-TAB cycle. Enter accepts the pick and closes the menu (a second Enter runs it); Esc restores the line.
See TAB Completion & Ghost Text for the key-by-key contract.
Presentation
NIU_COMPLETION_STYLE picks the shape. Styles are presentation-only; they do
not change the interaction above, except gnu, whose literal readline
behavior is intentionally inert to the interaction axis. Pick one with
export NIU_COMPLETION_STYLE=<name> in ~/.niubashrc or the environment (see
Configuration Sources & Precedence):
column(default) — multi-column grid. When any candidate carries a description (e.g. flag completions such asgit checkout -<TAB>), the whole list is shown as a single vertical column with each description beside its value.gnu(opt-in) — literal GNU readline: TAB completes the longest common prefix (a lone candidate completes outright); TAB again on an unchanged line prints the candidates as width-adaptive columns and repaints the prompt. The list is printed output, not a menu: nothing is selected, arrow keys stay on history, no popup.ide— multi-column popup with descriptions, VS Code style. Column count adapts to the terminal width; descriptions render beside their candidates.list— vertical list with descriptions (fish-style).inline— the candidate stays in the line and TAB cycles through the set in place (like bashmenu-complete).
show-all-if-ambiguous / show-all-if-unmodified-style readline variables
are not implemented. In select/cycle the menu appears on TAB #1; in
insert the second TAB is the listing. completion.page_size and
completion.behavior are internal implementation settings, not user-facing
options — there is no environment variable or config key for either.
Flag completions (ls --a<Tab> → --all with its description) come from the
bundle's generated completion assets and work in every style; ide and
list show the descriptions inline.
WinuxCmd Applet Completions
Every WinuxCmd applet ships with flag completion built into the niu binary:
grep --col<Tab> offers --color / --colour with descriptions,
ls --color <Tab> offers always / auto / never, and wpm <Tab>
lists the package-manager subcommands (install, search, uninstall,
...).
These definitions are generated from winuxcmd --help (WinuxCmd 1.1.5
transcripts) by scripts/generate-winuxcmd-completions.py, stored as one
TOML per applet under crates/niubash-runtime/assets/completions/winuxcmd/,
and compiled into the runtime — so they work on a fresh install with no
plugin enabled. When WinuxCmd gains applets or options, regenerate against
the new binary:
python scripts/generate-winuxcmd-completions.py --winuxcmd <path-to-winuxcmd.exe>
python scripts/test-winuxcmd-completions.py # golden check: corpus vs committed assets
The common external commands that are not WinuxCmd applets — git, docker,
kubectl, npm, and friends — are covered one layer up: the official
oh-my-niu bundle ships their subcommand/flag tables in its completions/
directory, so git co<Tab> offers checkout/commit/config once the
bundle is in place. (The hand-curated tables niu used to compile in for
these commands were removed with the 1.5.0 product-TOML deletion; commands
no layer covers fall back to path completion, and a user completion dir
can always supply a table of its own.)
Priority is layered: the embedded applet defaults are the base layer, and
completion definitions loaded later override them per command — a
bundle/pack TOML or a user completion-dir TOML whose file stem (or
command key) matches the built-in name replaces the built-in definition
entirely, so trimming or extending a command's flags is a plain file drop,
not a fight with the defaults.
AI Agent Skill Bundle
For AI hosts (Claude, ZCode, Cursor, ...) that drive your shell, niubash
ships a skill bundle describing its capability surface and dialect
contract: skills/niubash/SKILL.md plus references/. Install it without
hunting for the zip:
niu skill install # default: ~/.claude/skills/niubash/
niu skill install --target all # codex + claude + zcode + cursor
niu skill install --target C:/agents/skills # generic: <dir>/niubash/
niu skill status # current / outdated per target (byte compare + sha256)
niu doctor reports an advisory agent skill row. The released
niubash-skill-v*.zip contains the same tree (WinuxCmd-skill layout), so
unpacking the zip into an agent skills directory is equivalent.
The command tables inside the bundle are generated — hand-written lists
rot. scripts/generate-skill.py fills the GENERATED-marked regions of
SKILL.md and references/quickref.md from the engine's own surfaces:
a captured help -s '*' transcript (builtin table), a captured
niu --help transcript (launcher/plugin verbs), and the applet completion
inventory (178 winuxcmd applets). After changing the launcher help or the
builtin table, refresh and re-check:
cargo build && python scripts/generate-skill.py --capture --niu target/debug/niu.exe
python scripts/test-skill-bundle.py # golden check: regions + embed manifest
Prompt And Themes
Defaults are a floor, not an identity. The built-in prompt renders only
while nothing claims PS1. It has two faces: on Windows, a Git
Bash-compatible two-row prompt (green user@host, yellow cwd, cyan
(branch) git segment — see Getting Started);
elsewhere, a ruline template (user@host cwd symbol).
Whoever sets PS1 last owns the prompt completely — your own rc line, an
enabled oh-my-bash theme, or starship:
PS1='\u@\h \w \$ ' # your own prompt: simplest possible claim
eval "$(starship init bash)" # starship claims PS1 on its first prompt
Disabling the claim (niu plugin disable oh-my-bash, or a plain
unset PS1) lets the built-in floor render again. PROMPT_COMMAND alone
is not a claim — it is a pre-prompt hook; hooks that want the prompt set
PS1 themselves.
The floor itself is shaped by NIU_PROMPT_CWD_STYLE (home, full, or
basename; see Getting Started). External themes
style themselves through the bash-compatible PS1 channel — colors,
powerline glyphs, and git segments come from the theme, not the shell.
History
History lives in ~/.niubash_history (or the configured history path) and
follows GNU's model: every interactive session appends to the same file and
refreshes from it, so lines typed in another shell are visible to navigation
and to the history builtin. The explicit sync verbs are GNU's:
history -aappends this session's new lines to the file;history -npicks up lines other sessions appended;history -rre-reads the file into memory;history -cclears the in-memory list (the file keeps its lines until the session ends, when lines cleared this way are reconciled out of it).
There is no sharing mode to pick. The former NIU_HISTORY_MODE
shared/session/private switch was retired (niubash#572): it had no GNU
counterpart, its documented behaviors did not match the implementation (a
value set in ~/.niubashrc could never take effect because it was read
before the rc ran, and the session mode's "builtins can observe later file
updates" promise was not implemented), and its private mode's near-unbounded
capacity was silently truncated on reload. A NIU_HISTORY_MODE left in the
environment is now silently ignored.
Custom Key Widgets
A shell function can act as a line editor widget. Declare it in
~/.niubashrc with NIU_BINDKEYS (one key:widget entry per line):
niu_fzf_file() {
local file
file="$(fd -t f | fzf)" || return 0
NIU_WIDGET_RESULT="ni $file"
NIU_WIDGET_ACCEPT=1
}
NIU_BINDKEYS="Ctrl+X:niu_fzf_file"
When the key fires, the function runs with the current editor state:
- In:
NIU_WIDGET_BUFFER(current buffer) andNIU_WIDGET_CURSOR(byte offset). Both are temporary and restored afterwards. - Out:
NIU_WIDGET_RESULTreplaces the buffer (unset or absent keeps it; an empty string clears the line),NIU_WIDGET_CURSOR_RESULTmoves the cursor to a byte offset, andNIU_WIDGET_ACCEPT=1submits the buffer as if Enter had been pressed.
Keys are single-key sequences such as Ctrl+X, Alt+G, a plain character,
or escape forms like ^X. The function runs as ordinary shell code: aliases,
PATH, and your rc all apply. Unknown widget names in bundle bindkeys follow
the same contract, so plugins can ship function widgets too.
Shell-Function Completions
A shell function can provide completions for a command's arguments. Declare
it in ~/.niubashrc with NIU_COMPDEFS (one command:function entry per
line):
niu_git_comp() {
local branches
branches="$(git branch --format='%(refname:short)')" || return 0
NIU_COMP_RESULT="$branches"
}
NIU_COMPDEFS="git:niu_git_comp"
When completing arguments for a registered command, the function runs with:
- In:
NIU_COMP_WORDS(space-joined words, matching bashCOMP_WORDS) andNIU_COMP_CWORD(bashCOMP_CWORDsemantics). Both are temporary. - Out:
NIU_COMP_RESULT, one candidate per line, shapedvalueorvalue<TAB>description.
A NIU_COMPDEFS line can also name a directory (issue #306): every line
that resolves to an existing directory is loaded as a completion-definition
directory — <cmd>.toml files in the same schema as the embedded applet
definitions, and <cmd>.bash standard bash completion scripts (read as
data, never executed). Remaining lines are command:function pairs:
NIU_COMPDEFS="C:/agents/completions"
NIU_COMPDEFS="$NIU_COMPDEFS
git:niu_git_comp"
Compdef functions run synchronously during completion, while the line editor
owns the terminal. They must not print to stdout: compute with command
substitution and write NIU_COMP_RESULT instead. Bundle keybindings TOML and
NIU_BINDKEYS share the same widget vocabulary, so plugins and users can
compose the two contracts freely.
Git Prompt Performance
This section covers the Windows prompt faces; off-Windows the git segment renders empty and nothing in this section applies. The host computes the git segment once per prompt pass and hands the prompt the finished string; rendering never runs git. How the value is produced:
- inside a repository, one bounded spawn of the user's own git per pass
(
git status --porcelain=v2 --branch, 2 s timeout with the child killed,--no-optional-locks, stderr discarded). The user's git is a deliberate choice: sparse checkouts, submodules, linked worktrees and partial clones are only answered correctly by the git the user actually runs — an in-process library silently dropped the branch segment on old-owner repository trees before; - repaints within the same pass re-read that pass's computed value and spawn nothing;
- outside a repository nothing is spawned at all — the host only walks up
from the cwd looking for a
.gitmarker.
Prompt and theme plugins render the snapshot the host computed for the pass; they must not shell out to git themselves. If the prompt flickers or repaints the current line, debug the segment lifecycle rather than adding more inline Git calls to the theme.
Cross-pass caching and background refresh — recomputing only when the repository's HEAD/index state changes, with a late result landing on a later pass instead of being computed inside the current one — are planned (niubash#643, post-release batch) and are not part of the current build: today, every pass inside a repository pays its one bounded spawn, and no git value is carried across passes.
Plugin Workflow
Use the CLI to inspect the ecosystem instead of relying on stale docs:
niu plugin list # sources, their assets, activation state
niu plugin discover # read-only overview, including not-yet-installed managers
Enablement is per source or per asset (a theme), and it lands in the generated loader, not your rc:
niu plugin enable oh-my-bash # records the source; republishes ~/.niubash/generated/plugins.niu
niu plugin enable agnoster # a theme asset -> sets OSH_THEME in the loader
niu plugin disable oh-my-bash # manifest updated; the built-in floor returns
niu plugin update|sync|restore|clean are the lockfile-style maintenance
verbs for installed sources.
Third-Party Sources
Beyond the curated catalog (oh-my-bash, bash-it, bash-completion),
niu can install any git repository or local path that follows a known
plugin-manager layout. Installing is not activating: nothing a source
ships runs until you explicitly enable it.
niu plugin add https://github.com/someone/oh-my-bash-fork.git
niu plugin enable oh-my-bash-fork
niu plugin source remove oh-my-bash-fork # delete tree + registry entry
Notes:
- Sources are cloned to
~/.niubash/sources/<id>and registered in~/.niubash/sources/registry.json; the registry records the origin, ref, and path. niu plugin update <id>re-fetches the registered origin;niu plugin rollback <id>returns to the previous version.- A git ref can be pinned at add time with
niu plugin add <id> --ref <ref>. NIU_PLUGIN_SOURCES_ROOToverrides the sources root (portable setups and tests).
Command Discovery And WPM
Niubash resolves Unix-style commands through normal Windows PATH. When a
command is missing or comes from the wrong provider, inspect the active
installation:
command -v niubash
command -v winuxcmd.exe
command -v ls
winuxcmd.exe wpm index status
winuxcmd.exe wpm search jq
winuxcmd.exe wpm links rebuild --force
Do not assume /usr/bin exists. Niubash is a Windows process using Windows
executables and command links.
Elevated Commands
Elevation is a three-layer delegation (niubash#429): Niubash never elevates by itself — one of the layers below owns UAC, process creation, environment forwarding, and console handling.
-
The Rubash
sudobuiltin — off by default, opt-in only. The embedded engine's experimental elevation builtin stays disabled unlessNIU_ENABLE_RUBASH_SUDO=1is set before Niubash starts (or a host runsenable sudowith an elevation handler installed). It exists for host integrators and is not the recommended Windows path. -
Microsoft sudo — the in-box channel on current Windows. Windows ships
sudo.exefrom build 26045 onward (generally available with Windows 11 24H2); enable it under Settings → System → For developers → Sudo. Where present it is the preferred provider:sudo your-commandworks with no extra install. -
gsudo — the package channel, and the only one on Windows 10. The WPM
gsudopackage covers the machines Microsoft sudo never reaches:command -v gsudo gsudo --version gsudo your-command argsInstall or repair it through the active WPM provider when necessary:
wpm search gsudo wpm install gsudo wpm links rebuild --force
niu doctor reports which channel a machine actually has (the
elevation channel row), so a missing provider is visible before a
script depends on it.
Do not alias sudo automatically in shared scripts. A user who wants the
Unix spelling interactively can add this to ~/.niubashrc:
alias sudo='gsudo'
Windows Paths And Home
Prefer durable Windows paths in scripts:
cd C:/Users/you/repo
ls "C:\Program Files"
cd ~
Prompt display should normally render the home directory as ~ and descendants
as ~/path, but internal process paths remain native Windows paths. Treat
/c/Users/... as compatibility input, not the primary model.
$HOME stays in Windows form (niubash#522)
$HOME is deliberately the Windows-native form (C:/Users/you), not
the POSIX-persona form (/c/Users/you) that $PWD renders in. The two
spellings name the same directory, so inside your home directory
test "$HOME" = "$PWD" is false — that inequality is expected, not a
bug.
The Windows form is a contract, not an oversight: $HOME is exported
to every child process, and native Windows tools that receive it
(editors, Git, language runtimes, anything outside the shell) expect a
path they can open directly. The /c/... persona is a shell-side
compatibility spelling for input and display; most other programs
cannot resolve it.
Scripts that need the POSIX form of home convert explicitly, at the point of use:
# $HOME (C:/Users/you) -> persona form (/c/Users/you)
drive=$(printf '%s' "${HOME:0:1}" | tr '[:upper:]' '[:lower:]')
home_posix="/$drive${HOME:2}"
# and back: /c/Users/you -> c:/Users/you (drive-letter case is cosmetic
# to Windows APIs)
home_win="${home_posix:1:1}:${home_posix:2}"
If Git for Windows is installed, cygpath -u "$HOME" and
cygpath -w "$home_posix" do the same conversions. Conversely, when
handing a path to a native tool, pass $HOME-style Windows forms
as-is — do not pre-convert them to the persona spelling.
Updating
Keep the three update planes separate:
niu --self-update --check
niu --self-update
winuxcmd.exe wpm update winuxcmd
niu plugin update oh-my-bash
niu plugin rollback oh-my-bash
niu --self-updateupdates the shell.wpm update winuxcmdupdates command packages and command links.niu plugin update <source-id>updates an installed plugin source;rollbackreturns it to the previous version.
Debug Checklist
For shell issues, capture the active binary and execution path first:
niu --version
command -v niubash
command -v winuxcmd.exe
echo "$SHELL"
niu -c 'echo command-mode:$SHELL'
niu -C 'echo repl-command:$SHELL'
For repository changes, run focused tests before broad suites:
cargo test --test repl_command --locked
cargo test -p niubash-runtime --lib --locked
cargo test --test plugin_inventory --locked
Use Plugin System Direction for architecture and Plugin System Roadmap for execution order.
Configuration sources and precedence
Since 1.5.0 Niubash has no ~/.niubash/config.toml. The file is
never read at startup. Every setting has exactly one kind of source, and
niu config shows the effective value together with where it came from.
The three sources
| Source | What lives there |
|---|---|
| Environment | niu-proprietary NIU_* variables (NIU_COMPLETION_STYLE, NIU_COMPLETION_INTERACTION, NIU_COMMAND_NOT_FOUND_HINT, NIU_RC_POLICY, ...). Export them from ~/.niubashrc or the terminal environment. |
| inputrc | GNU readline variables and key bindings: $INPUTRC, else ~/.inputrc (set editing-mode vi, set keyseq-timeout 120, "\C-t": transpose-chars, ...). |
| rc | ~/.niubashrc shell code: bind, set -o, shopt, aliases, functions, plugin/theme lines. |
Anything not set by a source uses the built-in default. There is no second copy of a GNU knob in a niu file, and no niu file that can disagree with the rc.
Precedence
For niu-proprietary knobs the chain is simply:
NIU_* environment variable > built-in default
An invalid value prints one diagnostic and falls back to the default; it never breaks startup.
For readline state, Niubash follows GNU's order:
~/.niubashrc (bind / set -o) → $INPUTRC or ~/.inputrc → editor
The rc runs first, then readline initializes and reads the inputrc file.
That means an inputrc set editing-mode vi overrides a set -o emacs
from the rc, and inputrc bindings are visible to the line editor
together with rc bind lines. keyseq-timeout and the editing mode are
read from readline, not from any niu setting.
niu-proprietary settings
| Setting | Environment variable | Values | Default |
|---|---|---|---|
| TAB presentation | NIU_COMPLETION_STYLE | gnu, ide, column, list, inline | column |
| TAB interaction | NIU_COMPLETION_INTERACTION | insert, cycle, select | select |
| Command-not-found hint | NIU_COMMAND_NOT_FOUND_HINT | off, wpm | off |
| Personal-rc policy | NIU_RC_POLICY | primary-only, bashrc-fallback | primary-only |
| Floor prompt backend | NIU_PROMPT_STYLE | gitbash, template, segments | gitbash on Windows, template elsewhere |
| Segment preset | NIU_PROMPT_SEGMENT_PRESET | lean, classic, rainbow, pure, robbyrussell | classic |
| Left / right segments | NIU_PROMPT_LEFT_ELEMENTS, NIU_PROMPT_RIGHT_ELEMENTS | space- or comma-separated: dir, status, time, promptchar, osicon, context, backgroundjobs, cmdexectime, newline, git | the preset's order |
Example — put these in ~/.niubashrc:
export NIU_COMPLETION_STYLE=ide
export NIU_COMPLETION_INTERACTION=insert
The NIU_PROMPT_* knobs pick the floor prompt: the native prompt
Niubash draws while nothing claims the prompt slot. A non-empty PS1
(your own rc, an oh-my-bash theme, starship init bash) is a claim and
always wins; unsetting it brings the selected floor back. The selection
is re-read after the rc and after every interactive line, so an
interactive export NIU_PROMPT_STYLE=segments takes effect from the next
prompt and unset NIU_PROMPT_STYLE restores the factory floor:
# ~/.niubashrc
export NIU_PROMPT_STYLE=segments
export NIU_PROMPT_SEGMENT_PRESET=lean
export NIU_PROMPT_LEFT_ELEMENTS='dir git backgroundjobs promptchar'
NIU_RC_POLICY is read before any rc is sourced (it decides which
rc may be sourced), so a line inside the rc only reaches sessions
started from a shell that already exports it. To use
bashrc-fallback before the rc exists, set the variable in the
terminal environment (or the Windows user environment / shell profile).
niu setup --rc-policy bashrc-fallback prints the export line for
you to add yourself: niu never edits ~/.niubashrc (it is your shell
code, not a product database), and creating a primary rc to hold the
line would suppress the fallback it selects. A marked policy block
left in an rc by an older niu release is reported by the command and
left byte-identical — removing or replacing those lines is a hand
edit.
GNU-shaped settings
Bindings and readline variables belong in the rc or the inputrc file:
# ~/.niubashrc
bind '"\C-g": redisplay'
bind -x '"\C-t": my-command'
bind 'set keyseq-timeout 120'
set -o vi
# ~/.inputrc
set editing-mode vi
set keyseq-timeout 120
"\C-t": transpose-chars
$INPUTRC replaces ~/.inputrc for the whole process, exactly as in
GNU bash. There is no [keymap] section and no niu config set keymap.bind: the rc bind builtin and the inputrc file are the only
binding channels.
Inspecting settings
niu config is read-only:
niu config # same as `niu config list`
niu config get <key> # one line: key = value (source)
The source is env, inputrc, or default. Example:
completion.style = ide (env)
completion.interaction = select (default)
startup.rc-policy = primary-only (default)
editing-mode = vi (inputrc)
keyseq-timeout = 120 (inputrc)
niu config set ... was removed in 1.5.0. It now explains the
replacement: rc bind/set/shopt, an inputrc line, or an
export NIU_*.
Migrating a pre-1.5.0 config.toml
If ~/.niubash/config.toml still exists, interactive startup prints a
one-line notice naming the migration command. The file itself is never
read. Run:
niu config migrate
The migration:
- translates
[keymap].bindentries tobind '<spec>'rc lines and[keymap].unbindentries tobind -r '<key>'; - translates
command-not-found-hint,completion.style,completion.interaction, andstartup.rc-policytoexport NIU_*lines; - appends a commented
# >>> niu config migrate >>>block to~/.niubashrc(an existing block is updated in place, so running it twice never duplicates lines); - renames the old file to
config.toml.migrated-<UTC timestamp>(for exampleconfig.toml.migrated-20261030-034500Z).
Unrecognized values are reported as skipped instead of being guessed. A malformed file is refused and left byte-for-byte untouched. After a successful migration the startup notice disappears because the old name no longer exists.
niu setup no longer writes a config file either. Its completion
choices become export NIU_* lines in the rc it creates — and only
when no rc exists yet: over an existing rc the wizard parks the same
text as a proposal sample under ~/.niubash/ for you to apply by
hand, and niu setup --rc-policy only prints the export line
described above.
Plugins & the Bash Ecosystem
Niubash does not vendor a plugin framework. The plugin system is the external
bash ecosystem as first-class content: oh-my-bash, bash-it and
bash-completion install over git clone and expose their real
themes/plugins/aliases/completions through
their own selection mechanisms. Nothing is sourced until you enable it.
This page is the user guide; the last section is a compact quick reference for AI agents driving niu on a user's behalf.
The five nouns
| Noun | What it is | Where it lives |
|---|---|---|
| Source | A git tree installed by niu (a manager like oh-my-bash, or any single-purpose repo) | ~/.niubash/sources/<id>/ |
| Asset | A theme/plugin/alias/completion inside a manager source | enabled via the manager's own mechanism |
| Recipe | A data row describing one ecosystem asset and how to install it (~500-row compiled-in index) | niu plugin recipe list |
| Collection | A named manifest of recipe ids — a starting-point bundle (LazyVim-extras pattern) | built-in, or ~/.niubash/distros/ |
One install driver exists, and only one: git (tree sources, via
niu plugin add <git-url>). Niubash carries zero network/HTTP download
responsibility (download retraction, owner ruling 2026-10-04): executable
tools (fzf, starship, …) install through your real package managers —
wpm first on Windows (owner correction 2026-10-03), winget/scoop as
alternatives for what wpm does not carry (GUI apps, fonts), and
apt/dnf/yum/brew on other platforms. The recipe rows for those tools stay
in the index as catalog metadata and add prints the commands.
Everyday flow
$ niu plugin discover # read-only: what's out there
$ niu plugin add oh-my-bash # git-clones the manager
$ niu plugin list # sources, assets, activation state
$ niu plugin enable agnoster # activate a theme through oh-my-bash
The load-bearing rule: install and activation are separate
verbs. add/apply land content on disk but nothing from it executes in
your shell until you enable an asset explicitly. Collection applies honor
the same rule. (There is no trust/review gate — niubash#647 removed it;
what you install is what runs once enabled, exactly like cloning a repo
and sourcing it by hand.)
Manager sources (catalog ids like oh-my-bash) are also declared in the
spec ~/.niubash/plugins.json — the single source of truth for what is
declared; niu plugin sync reconciles the spec with what is installed,
and niu plugin update <id> (no id = all) moves sources to their ref tips.
What activation writes is never your rc (niubash#359, v1.4.2): every mutating
verb regenerates ~/.niubash/generated/plugins.niu — a deterministic,
validate-then-publish loader the host sources read-only before
~/.niubashrc, so user rc lines win. NIU_PLUGIN_LOADER=off disables
loading; legacy # >>> niu source managed blocks left in an old rc keep the
loader off until you remove them (niu plugin migrate-rc --diff diagnoses —
it never edits the rc either).
Imperative mode → adoption (1.3.1)
A machine with installed sources but no spec is in imperative mode: the
startup form stays silent (nothing to reconcile), and
niu plugin sync lists the state with the migration one-liner:
$ niu plugin sync --adopt
declared oh-my-bash (installed; adopted into the spec)
...
--adopt declares every installed-but-undeclared source, snapshotting the
live enablement (enable = [...]) and the active theme (theme = ...)
from the machine's current state, so the adopted spec round-trips — a
plain niu plugin sync afterwards is a no-op. niu plugin add <target>
on an already-installed source declares it (never the old "remove it
first" refusal), and the first-run wizard's collection apply now ends
spec-managed (the run itself adopts, picked theme included). Startup
installs that fail are memoized and not retried on every terminal —
explicit verbs retry.
Undo is printed with every mutating command (disable, source remove,
source rollback) and the setup wizard journals one undo
command per thing it changed.
Recipes: the index
$ niu plugin recipe list # the whole index
$ niu plugin recipe list --category prompt # manager|theme|plugin|alias|completion|prompt
$ niu plugin recipe list --json # machine-readable (agents: prefer this)
$ niu plugin recipe show starship # driver, version, license, state
$ niu plugin add starship # prints package-manager install commands
Rows with driver = git install as tree sources; executable-tool rows
(driver = "download" in the generated index) are catalog metadata —
add prints package-manager install commands (wpm first on Windows,
native managers elsewhere) and never fetches; rows with no driver are
info-only (e.g. ble.sh, which builds from source) and add explains
instead of installing.
Collections: starting points
$ niu plugin distro list # built-in + imported
$ niu plugin distro apply recommended
$ niu plugin distro import <git-repo-or-path> # any repo with niu-collection.json
$ niu plugin distro remove <name>
Built-ins: minimal (bash-completion only), recommended (oh-my-bash + its
default theme + completions — also offered by the first-run wizard),
full (both frameworks + bash-preexec; its fzf/starship entries print
package-manager suggestions, since niu downloads nothing).
A collection is a small JSON manifest of recipe ids:
{
"schema": "niubash:plugin-collection@1",
"name": "my-starter",
"description": "what this bundle is",
"entry": [
{ "recipe": "oh-my-bash" },
{ "recipe": "starship" }
]
}
Imports are first-class: anything the built-ins can do, your own repo can do,
byte-identically. Upgrading from a pre-1.5.0 niu whose imported collections
still use the TOML forms? Run niu plugin migrate once — it converts the
distro registry and every imported manifest to JSON and renames the old
files aside; nothing reads the TOML forms afterwards. The same one-shot
bridge also converts the plugin spec (~/.niubash/plugins.toml →
plugins.json, merged entry-by-entry by target) and the source registry
(~/.niubash/sources/registry.toml → registry.json, merged by source
id) — existing JSON entries win, legacy-only entries are carried over,
and the old files are renamed aside, never deleted. The same bridge also
converts the bootstrap-failure ledger (bootstrap-failures.toml →
bootstrap-failures.json under the sources root, merged by target) and
the mirror config (~/.niubash/mirrors.toml → mirrors.json; an
existing JSON config wins wholesale). apply installs every entry through its recipe driver —
installation only; activation stays an explicit enable. Failures are collected per
entry (a bad entry never kills the rest) and reported with the retry verb.
The first-run wizard's plugin-collection question is a LazyVim-style
progressive-disclosure hook: it only appears when the ecosystem is empty, and
Skip is the default.
When the picked collection installs a theme-bearing source (recommended/
full), the same wizard run immediately offers the theme pick — one run,
out of the box. The gallery lists the fresh
source's themes, and the pick lands through the same manifest +
generated-loader path a later niu plugin enable <theme> uses, journaled
with its own undo line. Declining (or Esc) changes nothing — the run prints
the re-run/enable follow-up instead.
Tools: package-manager recommendations
$ niu plugin add fzf # prints: wpm install fzf (Windows, first choice),
# winget/scoop alternatives, apt/dnf/brew,
# plus the upstream release URL
Nothing is fetched and nothing lands on disk — run the printed command with
your package manager. The retired niu plugin tool verbs fail with a
pointer here; a download-era install under ~/.niubash/tools/<id> can be
removed by deleting the directory.
The menu UI
niu plugin ui opens a menu-level UI (needs an interactive terminal):
sections ordered by what needs attention — sources whose tree is missing
first, then ready sources, installable recipes, collections, global verbs. Every
action in the menu is the same verb the CLI runs (the footer shows the CLI
equivalent of each); there is no UI-only logic. Rows read
[state] id — hint.
For AI agents (quick reference)
When driving niu on a user's machine:
- Prefer
niu plugin recipe list --jsonandniu plugin list [--json]for state; plain-text output is for humans and changes freely. - Install is not activation.
niu plugin add .../distro apply ...land content on disk but nothing executes until an explicitniu plugin enable .... There is no trust gate (niubash#647): once the user enables an asset, it runs as-is. - A source whose tree is missing cannot activate — suggest
niu plugin restore <id>. - Mutations print their undo (
disable,source remove,source rollback <id>). Surface those undo verbs to the user. niu plugin update <id>moves a source to its ref tip (no id = every source);niu plugin syncreconciles the spec with reality;niu plugin restorerebuilds from the lockfile pin in~/.niubash/sources/registry.json.- Exit codes: success
0; usage errors and refused operations (unknown id, builtin-name collision, non-ttyui) exit non-zero with a message that names the object and the repair verb. - Env overrides used by tests/tools:
NIU_PLUGIN_SOURCES_ROOT,NIU_PLUGIN_DISTROS_ROOT.
External Completion Providers
Niubash ships no third-party completion provider in its binary. The shell
provides the protocol; providers are data you source from ~/.niubashrc
— the same setup a bash or zsh user writes by hand. Any tool that speaks the
bash completion protocol integrates this way; carapace-bin below is one
example, not a special case.
The protocol surfaces
Three surfaces accept external completion code, all configured from the startup rc:
1. complete compspecs (the GNU builtin)
The engine implements the complete builtin, so standard completion
registrations work as-is:
complete -W 'status switch merge rebase' mytool # static wordlist
complete -f tar # any file
complete -d cd # directories only
Static compspecs serve candidates at Tab directly from the engine.
Dynamic hooks — complete -F func and complete -C command — register and
display correctly (complete -p), and -F functions execute inside scripts
through compgen -F; their resolution at the interactive Tab press is an
engine follow-up (see the rubash release notes). Until it lands, a
function-based provider should also speak the compdef protocol below.
2. compdef functions (NIU_COMPDEFS)
For providers that compute candidates with a shell function, the rc declares
a command:function mapping and defines the function. The function sees
NIU_COMP_WORDS (space-joined, bash COMP_WORDS semantics) and
NIU_COMP_CWORD; it writes back NIU_COMP_RESULT, one candidate per line,
as value or value<TAB>description — the description shows up in the
completion menu.
_mytool_comp() {
# a real provider would shell out here and translate its output;
# carapace's `value<TAB>description` fish output drops in unchanged
NIU_COMP_RESULT="start"$'\n'"stop"$'\n'"restart\tRestart the service"
}
NIU_COMPDEFS="mytool:_mytool_comp"
Candidates are filtered by the typed prefix; NIU_COMPDEFS holds one
command:function pair per line.
3. Completion definition files
<cmd>.toml (flags, subcommands, value sources — the richest surface) and
<cmd>.bash (standard bash completion scripts: the opts="..." line plus a
case "${prev}" block with compgen value lists) are parsed into the same
definitions the embedded base layers use. The files are never executed: both
formats are read as data.
A completion-definition directory is declared with a directory line in
NIU_COMPDEFS — the same variable that carries command:function pairs
(issue #306). Every line that resolves to an existing directory is loaded
(both file formats); every other line is a command:function pair. A user
mytool.toml overrides the compiled-in definition for mytool entirely:
# ~/.niubashrc — completion files as plain rc data
NIU_COMPDEFS="C:/agents/completions"
NIU_COMPDEFS="$NIU_COMPDEFS
mytool:_mytool_comp"
C:/agents/completions/mytool.toml # command/flags/subcommands TOML
C:/agents/completions/othertool.bash # standard bash completion script
Built-in base layers
Two compiled layers ship in the binary, so a fresh install completes common commands with no configuration at all:
- every WinuxCmd applet (
grep --col<Tab>→--color/--colour,ls --color <Tab>→always/auto/never) — generated from the applet--helptranscripts; - common external commands — git, tar, curl, ssh, docker, kubectl, and npm —
as static subcommand/flag tables (issue #305):
git co<Tab>offerscheckout/commit/config,kubectl get -<Tab>offers-o/--all-namespaces,curl -X <Tab>offers the HTTP methods.
Priority
GNU's own surface comes first, and it owns the command when present:
- Shell-function completers (
NIU_COMPDEFS, the compdef protocol) — niu's own overlay; it is the only layer that runs ahead of GNU programmable completion, and only because you opted into it. - GNU programmable completion — a compspec registered with
complete(including bash-completion's own registrations andinputrcrules). When one exists for the command, it is the only source of argument candidates: the static definition tables and the path fallback do not contribute, exactly as in bash. - Static definition tables — for commands without a compspec. Within these file layers a later definition replaces an earlier one per command: embedded winuxcmd-applet and common-command defaults → bundle definitions → user completion files.
- Built-in path / variable / command-name completion — the fallback of last resort.
So a provider can never shadow a compspec, and a compspec never has to compete with a table niu ships.
Example: carapace-bin
carapace-bin is a single binary carrying community completion specs for ~1200 commands (git, curl, gh, docker, ...). Its bash integration emits standard bash completion code, so the standard snippet is all it takes:
# ~/.niubashrc — requires carapace-bin installed, e.g.
# wpm install carapace-bin
# (or see https://github.com/carapace-sh/carapace-bin/releases).
# Until carapace is on PATH this block is a no-op.
if command -v carapace >/dev/null 2>&1; then
source <(carapace _carapace)
fi
niu setup offers this snippet as an opt-in (default off) — the wizard
writes the same block, it installs nothing.
Static compspecs from the snippet serve candidates today; the snippet's
complete -F hooks light up fully when the engine's interactive -F/-C
resolution lands. Providers that want description-carrying candidates
today can bridge through the compdef protocol — carapace's
carapace <command> fish <words...> output (value<TAB>description, already
prefix-filtered) matches NIU_COMP_RESULT's format line for line:
# compdef bridge: carapace data through niubash's function protocol
_carapace_bridge() {
local cmd
set -- $NIU_COMP_WORDS
cmd=$1
NIU_COMP_RESULT="$(carapace "$cmd" fish $NIU_COMP_WORDS 2>/dev/null)"
}
NIU_COMPDEFS="git:_carapace_bridge"
NIU_COMPDEFS="$NIU_COMPDEFS
docker:_carapace_bridge
curl:_carapace_bridge"
List the commands you care about — NIU_COMPDEFS is plain rc data, edited
any time.
TAB Completion & Ghost Text
How niu completes, key by key. The contract below is pinned by tests — if the shell ever surprises you here, that's a bug, not a feature.
Interaction: what TAB does
Completion has two independent axes: interaction (what TAB does to the
line) and presentation (how the candidate list is painted). The default
is the owner's zsh-style rule: select.
select (default) — zsh menu-select
TAB #1 queries the candidates once, puts the first candidate into the line and paints the grid with that candidate highlighted:
- TAB / Shift-TAB cycle through the frozen set (wrap-around).
- Down / Up move one row.
- Right / Left move one column; both edge directions wrap, as in zsh.
- Enter accepts the highlighted candidate and closes the menu — the candidate stays in the line, editable; a second Enter runs it.
- Esc rolls the line back to its pre-completion snapshot.
- A lone candidate completes outright and closes the menu.
- Bare TAB on a blank line inserts a four-space indent instead of opening the command-position grid.
The candidate set is frozen when the session starts, so cycling never
re-queries against the spliced text. This is a product rule: zsh's
menu-select starts with the first match selected; niu also enters that state
on TAB #1 rather than after oh-my-zsh's auto_menu delay.
insert — two-step common-prefix contract
TAB never shows you things you did not ask for:
- First TAB: complete and stop. The longest common prefix is spliced into the line and no menu opens. If that is all you wanted, Enter runs exactly what is on the line.
- Second TAB: show candidates. Pressing TAB again on the settled line opens the menu for the ambiguous set (or the completed directory's children).
- TAB with nothing to splice shows the menu immediately. When the typed text is already the whole common prefix, the menu is the disambiguation aid right away.
With the menu open, Enter commits the highlighted candidate into the line without running it; a second Enter submits. Esc keeps what was already inserted.
cycle — TAB cycles candidates
TAB #1 puts the first candidate into the line and opens the grid; further TAB / Shift-TAB steps through the frozen set with wrap-around. Enter accepts the candidate in the line and closes the menu — a second Enter runs it; Esc restores the pre-completion line.
Choose it with export NIU_COMPLETION_INTERACTION=insert|cycle|select in
~/.niubashrc or the environment.
Where candidates come from
GNU surfaces are authoritative, in this order:
- shell-function completers (
NIU_COMPDEFS, compdef protocol) — opt-in; - a GNU compspec registered by
complete(bash-completion included) — when it exists it owns the command's arguments, and neither the static tables nor the path fallback contribute; - niu's completion tables — the embedded winuxcmd applet tables first, then bundle and user completion dirs (the official oh-my-niu bundle carries the non-applet tables: git, docker, kubectl, npm, …) — only for commands without a compspec;
- path / variable / command-name completion.
The embedded tables are generated data (assets/completions/winuxcmd/*.toml),
not configuration: nothing about them is user-editable, and they never
override what complete registered.
Presentation styles
The style controls how candidates are painted; it does not change the
interaction contract above (the one exception is gnu, whose literal
readline behavior is intentionally inert to the interaction axis). Switch
any time; it takes effect on the next prompt:
export NIU_COMPLETION_STYLE=column # default: multi-column grid
export NIU_COMPLETION_STYLE=gnu # opt-in: GNU readline printed transcript list
export NIU_COMPLETION_STYLE=ide # VS Code-style popup with descriptions
export NIU_COMPLETION_STYLE=list # fish-style vertical list
export NIU_COMPLETION_STYLE=inline # candidate stays in the line and cycles
column(default) — multi-column grid. When any candidate carries a description, the whole list is shown as a single vertical column with each description beside its value.gnu(opt-in) — literal GNU readline: TAB completes the longest common prefix, TAB again prints a width-adaptive columnar list and repaints the prompt. Nothing is selected; arrow keys stay on history. This preset keeps that behavior regardless of the interaction axis.ide— multi-column popup with descriptions beside their candidates.list— vertical list with descriptions (fish-style).inline— candidates are inserted into the line and TAB cycles through them in place.
Put the line in ~/.niubashrc (or export it in the environment). The
environment is the only source for this knob — there is no config file
since 1.5.0. See
Configuration Sources & Precedence.
Ghost text (history autosuggest)
While you type, niu dims the rest of the most recent matching history entry after the cursor. It is a suggestion, never a commitment:
- Accept it whole:
→,End,Ctrl+E, orCtrl+Space. - Accept one word:
Ctrl+→. - Ignore it: keep typing — the ghost is display-only. TAB never takes
the ghost; it only completes filesystem/command candidates.
→always accepts the whole suggestion, so there is no plain "step past it".
The ghost and the grid never compete: while a completion menu is open, the ghost stands down; it returns as soon as the menu closes.
Enter with the menu open
Every menu interaction answers Enter the same way — the zsh complist / fish shape (niubash#821): the first Enter accepts the highlighted candidate into the line and closes the menu without running anything; the second Enter submits.
select/cycle: Enter accepts the highlighted candidate; press Enter again to run the completed line.insert: Enter commits the highlighted candidate into the line without running it; press Enter again to submit.gnu: the list is printed output, not a menu, so Enter always submits the current line.
With no menu open, Enter always submits what you see. A menu with nothing to accept (an empty or still-loading candidate set) does not claim Enter either — the key submits as usual.
Key bindings from other tools
niu mirrors GNU bind entries from your startup files into its line
editor, including the two shapes a flat keymap cannot express on its own
(niubash#630):
- Multi-key sequences (
"\C-x\C-e", fzf's"\C-\e("): delivered by a chord layer above the editor. The first unit is held only when a chord starts with it; a matching second unit fires the binding, and a non-matching one replays the held key followed by the new one, so nothing is swallowed. The window is readline'skeyseq-timeout(500 ms): past it the prefix is replayed on its own and the key stands alone. - Editing-mode toggles (
vi-editing-mode/emacs-editing-mode): these switch the session's machine for real. The other mode is built as a standby with the same widgets,bind -mentries and user keymap rules, so a flip keeps your bindings.
In emacs mode a bare ESC followed within ~50 ms by a key is read as the
meta prefix, the way a terminal sends M-x (ESC x); pressing Escape
alone keeps its immediate meaning.
Anything genuinely unusable — an unparseable sequence, an unknown
function — still produces a startup warning, with a per-item fix. Example:
eval "$(fzf --bash)" registers one binding of each shape (a multi-key
redraw-current-line binding and "\C-z" mode toggles for its fallback
macros); both now apply, and the rest of the integration works in full:
Ctrl+T (file widget), Ctrl+R (history widget) and Alt+C (cd widget).
Hooks
Status (2026-10, niubash#161): the niu-native named-hook registry described
by the previous version of this page is not implemented. The
niubash_add_*_hook registration helpers were part of the oh-my-niu
framework, which retired with the built-in plugin/theme stack
(niubash#145); there is currently no runtime registration path — the host
loads an empty hook configuration, so the internal run_*_hooks runners
have nothing to run. Whether (and how) hooks return for the
external-ecosystem world — e.g. registration builtins over the shell's own
function namespace — is an open owner ruling.
What exists today is the bash-native hook surface. External frameworks (oh-my-bash, starship, your own rc) already use it, and it behaves exactly as in GNU bash:
| Lifecycle point | Bash-native mechanism | Notes |
|---|---|---|
| before every prompt | PROMPT_COMMAND (function or string) | runs each prompt cycle, before the prompt is rendered |
| before a command executes | PS0 (expanded, printed) | after you press Enter, before execution |
| prompt identity | PS1 assignment | claims the prompt slot (defaults-as-floor: the product floor never fights an active claim; unset PS1 restores it) |
| directory change | chpwd-style: cd hooks via PROMPT_COMMAND + PWD diffing in your own function | no dedicated chpwd hook yet |
| signals / exit | trap 'handler' INT TERM EXIT DEBUG ERR | full bash trap semantics, via the engine |
| terminal title | write OSC escapes from PROMPT_COMMAND (or set NIU_TITLE) | NIU_TITLE, when set, is the value title logic sees |
Example — the starship shape (a PROMPT_COMMAND hook that claims PS1 in
the same render cycle):
# ~/.niubashrc
starship_precmd() { PS1="$(starship prompt)"; }
PROMPT_COMMAND="starship_precmd${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
eval "$(starship init bash)"
Example — time every command from PROMPT_COMMAND (start-of-command stamp
plus end-of-command report):
# ~/.niubashrc
__niu_t0=$SECONDS
__niu_timer_report() {
echo "last command took $((SECONDS - __niu_t0))s"
__niu_t0=$SECONDS
}
PROMPT_COMMAND="__niu_timer_report${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
Example — PS0 is expanded and printed right after you press Enter, before
execution (same expansion rules as PS1):
PS0='[running...] '
The internal runners (precmd/preexec/title/… cycle calls in
shell.rs) are retained: they carry the live machinery above
(PROMPT_COMMAND execution, PS0 rendering, PS1 claim/release sync,
title resolution) and keep the call sites for the eventual
external-ecosystem hook model. They are intentionally not a user-facing
surface until that model is ruled on.
Installer and Self-Update
Niubash ships the Windows release in two package shapes:
niubash-v<version>-win-<arch>-setup.exefor normal users.niubash-v<version>-win-<arch>.tar.gz/.7z/.zipfor portable, agent, or scripted use. Prefer the.tar.gz: it ships the bundled git/awk payload as real hardlinks, so it downloads and unpacks much smaller than the.zip, and Windows 10+ untars it natively (tar -xf ...). The.zipstays for tooling that only speaks zip.
Winget serves Niubash today: the per-user Inno Setup installer (x64 and arm64) installs with:
winget install --id Unixwin.Niubash
That installs 1.4.3. Manifests for 1.4.4 under Unixwin.Niubash
have been submitted and are in Microsoft's review queue; once they
merge, winget upgrade --id Unixwin.Niubash will follow new versions.
The setup.exe and portable archives above always carry the newest
build.
Scoop
Scoop installs the portable niubash-win-<arch>.zip (x64 and arm64) and
shims niu.exe onto PATH; the bundled winuxcmd tree stays inside the
Scoop app directory and resolves relative to niu.exe. The manifest is
submitted to the Extras bucket
(ScoopInstaller/Extras#19334,
in review). Once it merges:
scoop bucket add extras
scoop install niubash
scoop update niubash
Until then, install straight from the in-repo reference manifest
(installer/scoop/niubash.json, the same content as the Extras submission):
scoop install https://raw.githubusercontent.com/unixwin/niubash/master/installer/scoop/niubash.json
The manifest carries checkver (GitHub releases) and autoupdate
templates over the stable asset names, so the bucket follows each release
without a hand edit; the hashes come from the release's asset digests,
which equal the SHA256SUMS sidecar. tests/issue997_scoop_manifest.rs
ties those templates to the names release.yml publishes and the archive
layout scripts/package-release.ps1 stages, so a packaging rename fails CI
instead of breaking scoop update.
A Scoop install is updated by Scoop. Self-update normally reruns the
setup.exe installer with /DIR=<this install>, which would write an
Inno-registered tree (uninstaller, PATH entry, Windows Terminal profile)
into the directory Scoop tracks by version. So when Scoop's install receipt
(scoop-install.json, or install.json from older Scoop) sits next to
niu.exe, niu --self-update / self-update print
... managed by Scoop — update it with scoop update niubash and exit 0,
and the daily update reminder stays quiet — the same step-aside a Microsoft
Store install gets.
Linux (x86_64, aarch64) and macOS (aarch64, x86_64) ship as portable
.tar.gz archives that use the system's own tools — untar and run niu.
The installer is built with Inno Setup and installs per user by default under:
%LOCALAPPDATA%\Programs\Niubash
It does not require administrator privileges. The default installer tasks:
- add the install directory to the user's
PATH; - add or update a Windows Terminal profile named
Niubash; - set that profile's command line to the installed
niu.exe; - set that profile's starting directory to
%USERPROFILE%; - point the Windows Terminal profile icon at the installed PNG asset.
The Windows Terminal profile is installed by running:
niu --install-wt-profile --quiet
Users can run this command again after moving an install. To also set Niubash as the Windows Terminal default profile, run:
niu --install-wt-profile --set-default
Self-update uses Windows WinHTTP directly to follow the GitHub Release
releases/latest redirect, download the latest installer for the current
architecture, and start it silently. It does not depend on the GitHub REST API.
niu --self-update
Inside an interactive Niubash REPL, use:
self-update
The REPL command hands the update to a child process and exits the current
shell so the installer can replace niu.exe.
Useful dry-run modes:
niu --self-update --check
niu --self-update --dry-run
Interactive shells check for updates at most once per day. The check is
best-effort and silent on network failures; when a newer release exists, Niubash
prints a short hint to run self-update in the REPL or
niu --self-update outside it. Set
NIU_UPDATE_CHECK=0 or NIU_NO_UPDATE_CHECK=1 to disable the reminder.
The installer invokes winuxcmd.exe wpm links rebuild --root ... --force after
copying the files, so the bundled commands are materialized immediately. On NTFS,
WPM creates hard links to the installed winuxcmd.exe. The portable zip keeps the
first-start fallback: if command links are missing, Niubash runs
winuxcmd/activate-winuxcmd.sh once from the bundle.
The bundled package shims (usr\bin\gawk.exe, awk.exe) sit outside that
rebuild: wpm only reconciles names recorded in .wpm state, which the
product deliberately does not ship, so an upgrade that replaces
winuxcmd.exe under its own name would leave those links on the previous
image (niubash#468). The installer therefore runs
niu --relink-bundled-shims --force --quiet right after the rebuild, and
startup activation runs the same reconcile: every declared shim name is
brought back onto the current winuxcmd.exe image — relinked when stale or
missing, hardlinked when the payload delivered only a copy, and never
touched when the machine's own .wpm state owns the name.
Updating WinuxCmd with WPM
The Unix command set (ls, cat, grep, sed, ...) is delivered by
WinuxCmd and managed separately from the Niubash binary. Winux Package
Manager (wpm) handles it:
wpm update winuxcmd # update WinuxCmd from the local index
wpm index status # inspect the local index state
wpm list # indexed packages and install state
wpm update winuxcmd refreshes the command set in place; command links are
rebuilt automatically. Run wpm --help for the full surface (index,
source, search, info, install, links).
So the update story has two parts:
niu --self-update # the shell itself
wpm update winuxcmd # the Unix commands it ships with
Bash And sh Command Links
bash.exe and sh.exe are the shell itself under another name: where
hardlinks are available they are hardlinks to niu.exe, and the engine takes
the face from argv[0] ($0, BASH_VERSION, and POSIX mode for sh/ash).
That is worth real time - a hardlink costs nothing, while a forwarding launcher
runs one extra process on every bash -c / sh -c (measured at ~13 ms per
call, unixwin/niubash#377).
Run this after laying the tree down, and again after any update that replaces
niu.exe (a replaced binary leaves the names pointing at the previous inode):
niu --relink-shells --force
It links bash.exe and sh.exe in <root>\bin, <root>\winuxcmd\bin and
<root>\winuxcmd\usr\bin, skips directories that are not present, is
idempotent, and parks an existing name out of the way before replacing it, so a
shell that is running right now keeps its bytes. The Niubash installer does
this from [Run].
Where hardlinks are unavailable (exFAT, a network share) the shipped forwarding
shim stays the fallback. It sets NIU_INVOKED_AS=bash / NIU_INVOKED_AS=sh
and re-executes niu, which produces exactly the identity the argv[0] path
provides - keep both working instead of assuming either:
NIU_INVOKED_AS=bash
NIU_INVOKED_AS=sh
NIU_INVOKED_AS=ash
Niubash consumes that value before constructing Rubash; a plain niu.exe
launch must leave it unset, and a launcher must preserve all original argv
values rather than parsing shell options of its own.
Installer acceptance tests for either provider:
bash.exe -c 'test -z "$POSIXLY_CORRECT"'
sh.exe -c 'set -o | grep posix'
ash.exe -c 'set -o | grep posix'
This repository does not create the links inside a WinuxCmd tree by itself; the
installation provider calls niu --relink-shells (or implements the
NIU_INVOKED_AS contract above).
The PATH Entry Directory Contract
Only two directories of the installation ever appear on the process PATH:
{app} itself (so niu resolves) and <root>\winuxcmd\bin — the single
command directory. The contract for what may live in the command directory
(niubash#376):
- Hardlinks to the payload only, never forwarding launchers. A hardlink is
the same file — the spawn cost equals the payload's (
git.exethere measured 12.7 ms against a forwarding wrapper's 32.2 ms, unixwin/niu-git#8). A launcher re-executes the real binary and pays a full process per call, which removes the entire reason the entry exists. usr\binnever goes onPATH. It holds the whole Unix command set; putting it there shadowsgit,cygpath,find,sort,sedand friends in Git for Windows sessions and every GUI process.- The entry set is declared, not accumulated.
wpm links rebuild(installer[Run]) materializes the package-declared links, andniu --relink-shellskeeps the shell faces on the currentniu.exeinode. An undeclared link survives as a stale binary while the payload moves on. - Dead payloads are swept, not kept. Retired shapes —
*.bak-*and*.old-*left by earlier updaters, and*.niu-old-*, the relinker's park name when a crash lands between park and drop — are removed by the installer's[InstallDelete]/[UninstallDelete]sweeps; a directory onPATHmust stay auditable. The sweeps match only these generated shapes inside the two app-owned directories; a user file that borrows one of these suffixes there would be removed with them, so keep user files out of the installation tree.
Accepted limitation: in a GUI-launched process bash still resolves to the
WSL launcher (System32 and WindowsApps sit ahead of the user PATH);
sh and git resolve to the entry directory. Winning the bash name would
need a machine-scope PATH entry placed before System32, which a per-user
install does not do.
The Git Bash Slot Is Never Claimed
C:\Program Files\Git\bin\bash.exe is a convention slot that some IDEs may
resolve. A machine was found with an unowned, unsigned .NET shim parked there
forwarding into Niubash (niubash#398) — not placed by this installer and not
rebuildable from any repository. The ruling (PR #414, now pinned by
tests/installer_surface.rs and scripts/installer-slot-probe.py): the
install tree does not claim the slot.
- The installer runs with
PrivilegesRequired=lowestand never elevates, so it cannot write into an admin-walled directory likeC:\Program Files\Git\bin. installer/niubash.issmay not name an absolute foreign path at all; every write, delete, shortcut and[Run]surface stays inside{app}and Inno-managed shell folders, and the only registry value written isHKCU\Environment\Path.- A full install/uninstall cycle must leave every foreign slot byte-identical and leave no face name outside the removed tree. The cycle probe replays the executable installer steps in a user-directory sandbox and checks exactly that, so the ruling is a tested invariant rather than a promise.
Revisit only with evidence that an editor actually resolves that exact path and an accepted opt-in elevated task — the same stale-link class niubash#376 rule 5 bans otherwise.
Plugin Ecosystem In Packages
Release packages ship no plugin content. The built-in plugin/theme stack —
including the oh-my-niu bundle — is retired (niubash#145), and the plugin
verbs hard-bail on bundles, so staging one would lay down a tree the product
refuses to use (niubash#161). Packages contain the shell, the WinuxCmd
command set, and the command links.
The external bash ecosystem (oh-my-bash, bash-it, bash-completion, wild
plugins) installs on explicit user command — niu plugin add <id> clones
from upstream into the user profile. There is
nothing to pre-stage and nothing to update with the shell.
Using Git With Niubash
Niubash ships a real git — niu-git, the
git-for-windows C source rebuilt with MSVC — so a fresh machine has a working
git with zero setup. Two questions come up once you already have another git
(Git for Windows, a scoop git) or want niu's git from outside the shell:
- Which git does niu use? — the bundled one by default; yours, with one switch.
- How do I use niu's git from other programs?
— one PATH entry, never
usr\bin.
Which git does niu use?
git inside niu resolves through PATH, like every external command —
and so does the prompt's git segment, which spawns git by name, so both
always agree. The resolution order is:
- The bundled niugit wins by default. At startup niu injects the
bundled command directories ahead of the
PATHit inherited, and nothing is moved back in front of them: the bundled commands — git included — are the highest-priority commands in the shell, ahead ofSystem32and of anything else on yourPATH. That is deliberate: the bundled commands are built for niu's POSIX argument handling, and a same-named program elsewhere onPATHsilently taking over has caused real breakage before.gittherefore resolves to<root>\winuxcmd\usr\bin\git.exe(niu-git), and on a machine with no other git everything works out of the box — that is the point of bundling it (niubash#209). - Your own git wins with one switch. Set
NIU_USER_PATH_FIRST=1in the environment niu starts with, and the bundled directories are appended behind your inheritedPATHinstead of prepended. YourPATHorder then wins wholesale: your git — with its own configuration (credential.helper,core.editor, GPG, SSH keys all behave as outside) — and equally your ownbash,grep, and everything else you placed ahead. The bundled commands stay onPATHas a fallback for names you don't provide. This is a whole-PATHdecision, not a per-command one: niu never promotes a single command's directory, because a directory that holds your git often holds other programs too — a scoop shims directory carriesbash/shalongsidegit— and promoting it for git's sake once shadowed niu's ownbash/shwith Git for Windows' (niubash#1050).
Check which one you are on:
which git # ...\winuxcmd\usr\bin\git.exe, or your install's path
git --version # niugit builds self-identify as ...windows.N.niugit
To use your own git, have it on PATH before niu starts, as you already
would, and set NIU_USER_PATH_FIRST=1 in the environment niu starts
with (your user environment variables, or your terminal's profile) —
the switch is read once, at startup, when the bundled directories are
injected.
How do I use niu's git from other programs?
The install exposes exactly one directory to the process PATH:
<root>\winuxcmd\bin — the PATH entry directory
(installer.md, niubash#376).
Everything a package installs has a hardlink there, and git is no exception:
- From v1.5.1 the package ships the entry links themselves, so a fresh
install already has
<root>\winuxcmd\bin\git.exe(niubash#1052 — the 1.5.0 packager dropped them;wpm install niugitinside niu produces the same links on 1.5.0 and earlier). - Point other programs at that directory and they resolve niu's git directly:
add
%LOCALAPPDATA%\Programs\Niubash\winuxcmd\bin(per-user install) to the userPATH, or configure your IDE/editor's git path to<install>\winuxcmd\bin\git.exe. The entry link is the git binary — a hardlink, not a launcher — so calling it from anywhere costs the same as callinggit.exeitself (12.7 ms measured vs 32.2 ms through a forwarding wrapper, unixwin/niu-git#8).
Do not put winuxcmd\usr\bin on PATH. It holds the whole Unix command
set; on a machine that also has Git for Windows, its find, sort, sed,
cygpath would be shadowed in every Git Bash session and GUI process — the
exact collision the entry-directory contract exists to prevent
(installer.md).
Keeping both gits is also fine and needs no decisions: leave your Git for
Windows (or scoop git) directory wherever it is on PATH for other programs,
and niu will use that same one inside the shell (see
above). The bundled niugit stays as the fallback
for machines without any other install, and wpm keeps it up to date with
wpm update winuxcmd.
Accepted limitation (same as the installer contract): in a GUI-launched
process bash still resolves to the WSL launcher, because System32 sits
ahead of the user PATH; git resolves to whichever directory you put on
PATH as above.
Rubash Bash Compatibility Matrix
This matrix keeps the boundary clear: rubash owns shell language semantics, while Niubash owns Windows host integration, REPL behavior, completion, plugin routing, and winuxcmd command discovery. Use it when deciding whether a fix belongs in rubash or in the Niubash host layer.
Verification Layers
| Layer | Scope | Current evidence |
|---|---|---|
| Local compat fixtures | Focused Niubash binary tests for common bash semantics that depend on rubash plus winuxcmd command links. | CARGO_TARGET_DIR=target/codex-verify-phase17 cargo test --test compat --locked -- --ignored passed 18/18 on 2026-07-31. |
| Host contract tests | Windows process, cwd, stdin, script, env, and stdio behavior around rubash execution. | Covered by tests/host_contract.rs; full workspace test passed in the Phase 16 verification run. |
| GNU Bash upstream local gate | Broader upstream bash fixture from a sibling rubash checkout, intentionally local-only and not vendored. | docs/planning/bash-upstream-local.md records the Niubash local gate; the current rubash upstream ledger is the rubash README "Compatibility at a Glance" section: 83/83 suites pass on the 2026-10-12 full re-run (rubash master 764b9dde) — 62 byte-identical stdout on Windows, 20 environment-attributed, and the nameref suite's single residual line proven to be GNU Bash's own coproc reap-timing race. rubash CI also replays the upstream corpus on Linux on every push. |
Focused Compat Fixtures
| Capability | Evidence fixture(s) | Status | Boundary |
|---|---|---|---|
| Variables and simple parameter expansion | var_expansion, string_param | Passing | rubash parser/executor. |
| Command substitution | command_substitution, command_substitution_quoted_newline, command_substitution_function_pipeline | Passing | rubash command substitution; host still owns -c quoting and process invocation. |
| Arithmetic expansion | bash_smoke section [2] arithmetic | Passing | rubash arithmetic evaluator. |
| Indexed arrays | bash_smoke sections [3] arrays, [16] array slice | Passing | rubash arrays and parameter expansion. |
| Associative arrays | bash_smoke section [4] assoc arrays | Passing | rubash declare -A and associative lookup. |
| Boolean list status | and_or_status, bash_smoke section [20] exit status | Passing | rubash &&, ` |
| If / elif / else | if_else, multiline_if, bash_smoke section [11] if | Passing | rubash compound commands; Niubash must feed full scripts to rubash. |
| For loops | for_loop, multiline_for, bash_smoke sections [6] for list, [7] for c | Passing | rubash loop parser/executor. |
| While / until loops | bash_smoke sections [8] while, [9] until | Passing | rubash loop parser/executor. |
| Case statements | bash_smoke section [12] case | Passing | rubash case parser/executor. |
| Functions | function, command_substitution_function_pipeline, bash_smoke section [10] function | Passing | rubash function definition and invocation. |
| Aliases | alias | Passing | Niubash installs aliases into rubash; expansion is rubash-owned. |
| Pipelines | pipeline, command_substitution_function_pipeline, bash_smoke section [13] pipeline | Passing | rubash pipeline execution plus winuxcmd command links. |
| Redirection | bash_smoke section [14] redirect | Passing | rubash redirection with Niubash/winuxcmd filesystem behavior. |
| Heredocs | heredoc | Passing | rubash whole-script parsing; host stdin/script path must avoid line-by-line splitting. |
| Backslash continuations | continuation | Passing | rubash whole-script parsing. |
| Echo flags | echo_flags | Passing | shell builtin behavior as exposed through rubash/niubash. |
| Export to Windows child process | bash_smoke section [19] export | Passing | rubash environment plus Niubash process environment synchronization. |
| File tests | bash_smoke section [18] file tests | Passing | rubash test builtin plus host filesystem paths. |
Host Contract Coverage
| Host surface | Evidence | Notes |
|---|---|---|
| cwd authority | cwd_cd_pwd_and_windows_child_process_agree, drive_only_cd_and_bare_drive_commands_switch_to_drive_root | Niubash normalizes/synchronizes shell PWD with Windows child process cwd. |
| startup isolation | winshrc_does_not_run_for_non_interactive_modes | Non-interactive -c, script file, and stdin script paths do not source REPL startup rc. |
| temporary assignments | temporary_assignment_reaches_nested_niubash_child | Assignment semantics are observable by nested Niubash child processes. |
| stdin scripts | piped_stdin_without_args_runs_plain_script_surface, piped_stdin_without_args_runs_multiline_compound_block, piped_stdin_without_args_runs_heredoc_as_one_chunk | Host feeds complete stdin scripts to rubash for multiline/heredoc semantics. |
| script positional parameters | script_file_args_populate_positional_parameters | Host script path preserves $0/positional parameter behavior. |
| Windows child env | exported_env_reaches_windows_child_processes, sourced_rc_keeps_winuxcmd_visible_to_windows_children | Niubash bridges rubash env changes into Windows child process launches. |
| stdio and exit code | stdout_stderr_and_exit_code_are_preserved, closed_stdout_pipe_does_not_print_broken_pipe_error | Host preserves process surfaces expected by agents. |
| command-mode parsing edge cases | command_mode_accepts_base_prefixed_arithmetic_in_function_body, command_mode_parameter_pattern_removal_handles_escaped_quotes, command_mode_set_positional_splits_custom_ifs | Focused regressions for rubash-facing -c script delivery. |
Known Gaps and Routing
| Gap | Route |
|---|---|
| Full GNU Bash upstream gate is local-only and not normal CI. | Keep using docs/planning/bash-upstream-local.md for the Niubash local gate; source rubash suite numbers from the rubash README compatibility ledger. Do not vendor upstream bash tests. |
niu -c still has host-side rough edges around POSIX assignment prefixes, env VAR=value cmd, heredoc temp-file flows, and complex quoting in agent commands. | Track as Niubash command-mode/host issues, not as rubash language failures unless a direct rubash fixture reproduces it. |
| Job control and interactive terminal process-group semantics are not covered by the focused compat matrix. | Route through rubash first; add Niubash host tests only for Windows process integration. |
| Plugin runtime behavior is intentionally outside current shell compatibility scope. | Keep in plugin docs; do not mix with bash language compatibility claims. |
Windows read/$( ) strip a trailing CR (\r\n line endings in piped/redirected input are normalized away) — GNU bash passes bytes through verbatim. | Intentional host deviation (niubash#521): CRLF text is the native Windows interchange format; byte-transparency would surface stray \r into every variable read from a Windows-produced file. Documented here rather than "fixed"; revisit only if a consumer needs byte-exact GNU behavior, in which case route it as an opt-in flag, never as a default change. |
Maintenance Rules
- Add one focused fixture under
tests/compat/fixtures/before claiming a new bash-language capability in README or roadmap. - Prefer host contract tests for Windows cwd/env/stdin/stdout issues that happen around rubash rather than inside rubash.
- Re-run the ignored compat suite before updating this matrix:
CARGO_TARGET_DIR=target/codex-verify-phase17 cargo test --test compat --locked -- --ignored. - Use the upstream local gate only when parser/executor behavior changes or when syncing a new rubash revision.
Performance
Measured, not claimed. Every number on this page is pinned to the issue or PR
that produced it, and the gates that keep it honest are named. The engine-side
ledger lives in rubash's
docs/performance.md;
this page is the host-facing summary, kept in step with the README's
Performance section.
Windows spawn cost — one hidden console per session
A console-less session (direct niu -c, detached, CI) used to pay a hidden
console allocation on every external spawn, ~22 ms per child (design and
shape in niubash#462). The
fix landed engine-side
(rubash#913, shipped in v1.4.2):
a windowless console is pre-allocated once on Windows 11 24H2+/Server 2025
(AllocConsoleWithOptions), or adopted from the first CREATE_NO_WINDOW
child (AttachConsole) on older builds — an entire niu -c 'a; b; c' tree
pays at most one allocation and later spawns inherit it. 14 regression tests
pin zero visible windows and the scaling behaviour (rubash
tests/console_window_gate.rs). The same release closed the per-command
console flash through launchers (niubash#379 → rubash#668, WinuxCmd#1282) that
the agents page names as the Claude Code failure.
$(tput …) terminal queries answered in-process
The inline tput whitelist arm
(rubash#884) answers admitted
TERM×capability shapes in-process, byte-equal to GNU ncurses (269-row
differential matrix, diff = 0; 8 regression tests). On the ticket probe — 64
tput calls through command substitution — wall time fell 1165 ms → 47 ms
(~25x, zero spawns). The winuxcmd-side twin removed the ~17 ms per-call i18n
overhead in the real binary (~0.4 ms in-process after the fix; 3208-row replay
byte-identical:
WinuxCmd#1269). The other
harvest SLOW face — read on EOF, ~4.8 s/call — stays open on
rubash#800.
Engine hot paths
The embedded rubash engine; each fix carries its measured delta and a GNU differential battery:
- Multi-word literal command fast path:
[ 1 -eq 2 ]×20k ≈177→155 ms (rubash#967). [[ ]]direct numeric leaf + decimal fast path: 50k[[ 1 -eq 2 ]]1.41x→1.10x vs GNU (rubash#966).- Whitelist-skip of the procsub metadata scan: 1.56x→1.39x (~11%) (rubash#974).
- Decimal-subscript array write lane: interleaved 8k 3.65x→3.16x; also fixes a
real double side-effect in
a[$((i++))]=v(rubash#959). - Case: head-only
$BASH_COMMANDrender: 20-arm ×10k −10%, plus the divergence fix (rubash#958).
The interpreter triage behind that wave is closed with numbers: scalar
assignment ~1.06x GNU (rubash#609 → #672/#678), arithmetic loops and parameter
expansion via rubash#607/#608 (#665/#671/#679, #666 — ${s^} alone ~6x
faster), and the O(n²) array element write became O(1) amortized
(rubash#618/#616: associative 5000-key writes 445x→9.9x vs GNU, indexed
736x→3.8x). The export/unset fast-lane family landed
(#917/#918/#920, reworked for correctness in #943 — the per-op reduction the
v1.4.3 changelog notes);
rubash#916 stays open on the
residual.
Startup — the 2026-10-28 perf round (Linux, same machine)
The 2026-10-28 perf round re-ran the startup adjudication: 50-sample
interleaved runs of release builds on one Linux machine (sampling gate:
load1 ≤ 2.0, no other cargo/rustc), niu at master c06b2a08 embedding
rubash 231ffe1a, against a self-compiled GNU bash 5.3.20 oracle.
These are Linux same-machine numbers; they say nothing about Windows
magnitudes.
| shape | niu | rubash | GNU bash 5.3.20 |
|---|---|---|---|
| bare run (p50) | 3.71 ms | 3.28 ms | 2.60 ms |
-c 'true' (p50) | 4.14 ms | 3.59 ms | 2.67 ms |
The headline is the bare run: 16.98 ms in the 2026-10-25 baseline →
3.71 ms — the non-interactive fast path
(niubash#562) works as
designed, and niu bare startup now sits at the bare engine's level. The
-c 'true' row is ≈ baseline for all three shells. Engine-side detail
from the same round — the 30-case A-table, the pattern-op and
element-write fixes — lives in rubash's
docs/performance.md;
the corpus and raw results live in
shellbench.
Residual round close-out — 2026-10-29 (Linux, same machine)
The perf round's residual batch has closed out (the fixes land engine-side in rubash; niu inherits them with the engine). Same caliber family as above: release builds, Linux same-machine interleaved sampling — the residual batch sampled in same-window pairs under ambient load, so ratios and growth factors are the verdict basis.
- Associative-array element reads no longer scale with table size: a
${m[key]}miss at 10,000 entries measures 18.3 µs against GNU's 13.4 µs, flat in n; the length form${#m[key]}had its growth factor cut from ×10.67 to ×1.08 on misses. The mechanism is a settled read on the combined table — the typed cell mirror answers hits and misses authoritatively (rubash PR #1919, merged; the length legs in residual-batch PR #2060, merged). Full account in the engine ledger. - Command-completion candidates are cached:
compgen -con a fat PATH (~3,100 candidates) fell from 110.6 ms to 13.6 ms per call (GNU measures 277.6 ms in the same window); the walk re-runs only when the PATH/cwd fingerprint changes. - Large grouped scripts load faster: an 8,000-line function-definition group — the grouped shape heavy startup scripts such as nvm.sh exercise — reads in at 0.533 s, down from 3.248 s; the grouped reader no longer re-tokenizes the accumulated logical line per physical line.
- Honest floor, unchanged: plain command dispatch still carries the ~2.83–2.95× A-table floor tax against GNU (tracked in rubash#682). The filed "procsub read at 68×" figure did not reproduce on current master: draining a procsub costs 1.3 µs/line, and the while-read residual prices the same across file and pipe sources — it is this floor tax, not a procsub defect.
Android baseline — measured, honest, not yet re-measured
On a Termux aarch64 tablet, niubash 1.4.0 vs GNU bash 5.3.20 (niubash#352 — full method and matrix in the issue: same script file per shell, interleaved runs, best-of-3; startup rusage median of 20-30 warm runs):
| Workload | niu vs GNU bash 5.3.20 |
|---|---|
| Interpreter-bound (arith-for, string expansion, scalar assignment) | 2.3–3.7x slower (up to 7.3x on ${x^^} itself) |
niu -c true startup | 21.1 ms vs 8.3 ms (median of 30) |
Peak RSS (VmHWM, plain shell) | 10.2 MB vs 4.6 MB (2.2x) |
| Fork-bound (command substitution, pipelines) | up to 5.2x faster |
| Real script (500× mkdir/write + read-back) | 2.1x faster |
Both halves of the attributed gap are closed since the measurement: the
engine-side root causes (rubash#607-609, above) and the wrapper's one-shot
startup gap (niubash#351 —
niu -c was building a never-rendered prompt whose width query spawned two
tput processes on non-tty paths; after the fix niu -c true measures
15 ms vs bash 13 ms, zero tput spawns).
niubash#349 is the original
~2.1x arithmetic/function datapoint this pass grew out of.
No post-fix re-measure on Android hardware exists yet — #352 stays open for that re-run, and the Android leg still ships build-verified only (see Platform Support).
What keeps these numbers honest
- The release pipeline runs the
perfbudgetgate — every asset inscripts/perf/budgets.jsoncarries a measured budget (healthy themes re-render in 11-35 ms; the budget line is 120 ms; 5x over is a hard fail), and a breach fails the release. A nightly run watches the trend. - Perf canaries ride the engine's CI regression suite
(
cargo test --test regression), GNU-differential batteries ship with each fix, and the harness discipline (min-of-N, interleaved runs, same-tree release binaries) is written into rubash's ledger.
Built-ins & Fast Paths
Niubash resolves a command word through three layers, in priority order. This page documents what lives in each layer, how the inventory is kept honest, and where the inventory overlaps with WinuxCmd.
| Layer | What it is | Introspection (type, command -v, enable) |
|---|---|---|
| Real built-in | Runs in-process, no child process. Listed in the rubash whitelist (src/executor/builtin_names.rs). | Reports as builtin |
| Fast path | Hidden optimization: runs in-process only for simple argument shapes; falls back to the external WinuxCmd command otherwise. Deliberately not in the whitelist. | Reports as external — same as GNU Bash, where these commands are external too |
| External command | Resolved via PATH, provided by WinuxCmd (176 commands; 178 applets including the internal wpm and [). | Reports as external |
Real built-ins (64)
All 61 GNU Bash 5.2 built-ins are covered — none missing. The entries below that are not part of Bash are deliberate extensions:
| Group | Commands |
|---|---|
| GNU Bash 61 built-ins (all aligned) | . : [ alias bg bind break builtin caller cd command compgen complete compopt continue declare dirs disown echo enable eval exec exit export false fc fg getopts hash help history jobs kill let local logout mapfile popd printf pushd pwd read readarray readonly return set shift shopt source suspend test times trap true type typeset ulimit umask unalias unset wait |
| zsh compatibility extension | setopt unsetopt |
In-process env | env (coreutils semantics, sorted output, -0) |
| Windows-only | sudo (not counted in the 64) |
Notes:
declare/typesetandsource/.are alias pairs;[is implemented by thetestbuiltin and validates the closing].time,[[, and((are reserved words / grammar, not built-ins — same as Bash.timehonorsTIMEFORMAT.- The
sudobuilt-in is a Windows-specific extension (#[cfg(windows)]).
Fast paths (hidden built-ins)
These run in-process for simple argument shapes and fall back to the external WinuxCmd command otherwise. They are intentionally excluded from the whitelist so that introspection keeps reporting them as external, matching GNU Bash:
| Command | In-process behavior | Fallback |
|---|---|---|
sleep | Fractional seconds supported | external sleep |
dirname | Plain paths | external dirname |
basename | Plain paths | external basename |
env is the one hybrid: it is on the whitelist (reported as a built-in),
but its implementation is fully in-process with coreutils semantics and no
external fallback path.
Two additional reproduction built-ins exist for test compatibility only:
recho and zecho (mirrors of the helper built-ins in GNU Bash's own test
suite; not shipped in official Bash builds).
Overlap with WinuxCmd
Thirteen command names exist both as rubash built-ins/reserved words and as
WinuxCmd external commands: echo env kill printf pwd test [
true false (real built-ins), sleep dirname basename (fast paths),
and time (reserved word).
The overlap follows Bash semantics: inside a script the built-in or reserved
word shadows the external command, while explicit forms such as
command env or /usr/bin/env still reach the WinuxCmd external version.
Both implementations were compared option-by-option (escapes, format
specifiers, signals, jobspec, TIMEFORMAT) on 2026-09-08 — aligned.
How the inventory stays honest
The authoritative machine-readable lists live in
docs/builtins.md on unixwin/rubash.
A doc-sync test inside src/executor/builtin_names.rs parses that document
and fails cargo test whenever the whitelist or the fast-path dispatch
changes without the document being updated — and vice versa. Adding,
removing, or reclassifying a built-in therefore requires touching both the
code and the doc in the same change.
Niubash v2 Architecture
A native, Bash-compatible shell built on rubash + winuxcmd — Windows flagship, Linux and macOS shipped beside it
Positioning
Niubash is a native, non-isolated, Bash-compatible shell for both humans and agents — released for Windows (x64, ARM64), Linux (x86_64, aarch64), and macOS, with Windows the flagship. It does not implement the shell language itself — it is the interactive front end to the rubash lib (the bash-compatible engine) plus the routing layer onto winuxcmd (coreutils). Its core value is the Windows-native process/environment experience: a ruline REPL, the completion system, the prompt floor, Ctrl+C handling, terminal integration, and a stable non-interactive agent execution contract.
Niubash is not an MSYS2, Git Bash, Cygwin, or WSL-style isolated
environment. ~ points at the normal user home (USERPROFILE /
dirs::home_dir()); PATH, cwd, env, stdout, stderr, and exit codes are
ordinary host process state.
Three-layer architecture
niu.exe
├── Niubash host layer (Rust)
│ ├── rubash::Executor ← shell language engine (lexer/parser/execution/builtins)
│ ├── ruline REPL ← line editing, history, completion
│ ├── completion/ ← shell definitions + bash auto-import + 3-level cache
│ ├── prompt/ ← prompt floor (defaults-as-floor, §14.5 of the ecosystem design)
│ ├── config ← legacy/managed machine-state reads
│ ├── plugins ← external bash-ecosystem sources (add/enable, no bundles)
│ └── ctrl_c ← Win32 Ctrl+C handling
├── rubash lib (Rust)
│ ├── lexer/parser/ast
│ ├── executor (pipeline/redirect/alias/function/array/job)
│ └── builtins (cd/source/export/set/test/printf...)
└── winuxcmd.exe (C++) ← Unix coreutils (ls/cat/grep/find/cp/mv...)
Key design decisions
1. rubash as a lib dependency
Niubash links rubash directly as a Rust crate dependency:
[dependencies]
rubash = { git = "https://github.com/unixwin/rubash.git", branch = "master" }
All shell semantics (parsing, execution, built-ins, variable expansion, redirection, pipelines, job control) are delegated to rubash. Niubash does not re-implement lexer/parser/ast/builtins.
2. WinuxCmd is selected by Niubash and integrated via PATH
PATH is the default route and the fallback — the rubash Executor finds
external commands through PATH, whose semantics are the equivalence
reference. (An opt-in in-process FFI route, niubash#567, was removed
before 1.5.0 per the #727 ruling; PATH injection is the only route.)
Version selection is a Niubash session/config responsibility. At
startup:
- Read the explicit
WINUXCMD_PATH, then fall back to Niubash's own install/bundle/PATHdiscovery rules to locate awinuxcmd.exe. - Prepend the directory of that same exe to the process
PATHso that command links such asls/cat/grepresolve. - Pass the exact resolved exe path to rubash via
Executor::set_winuxcmd_path.
Rubash never guesses a different winuxcmd.exe from PATH. This way, stale
command links from an old bundle that are still on the Windows PATH can
never mix the dispatcher with the wrong links.
3. Windows real installation tree
Niubash derives one shell root from the selected installed
winuxcmd.exe. For example, the executable
<install>/usr/bin/winuxcmd.exe makes <install> the root. Niubash creates
the ordinary directories below that root:
<install>/usr/bin
<install>/bin
<install>/usr/local/bin
<install>/etc
<install>/var
<install>/tmp
<install>/dev
<install>/.wpm
usr/bin is canonical for WinuxCmd, WPM, command links, and filename-only WPM
targets. Explicit package targets keep their requested real directory.
Niubash passes the selected installation root to Rubash through
NIU_ROOT; there is no second ~/.niubash/root tree and no provider
union. Rubash maps /, /bin, /usr/bin, /etc, and /tmp directly below
the real root. /dev/null maps to Windows NUL; other /dev entries remain
unsupported capabilities.
4. Completion is independent of the engine
The completion system (shell definitions + bash script auto-import +
cmd -h description scraping + a 3-level cache) is implemented on the
Niubash side and does not depend on rubash. It is one of Niubash's core
differentiators.
5. Configuration and startup entry points
~/.niubashrcis the primary interactive entry point. Plain niubash/bash syntax declares plugin lists, theme, prompt template,export,alias, functions, and local startup logic.~/.niubashrcis also the only entry point: pre-rename legacy rc names and~/.bashrcare never read, migrated, or written — a session without~/.niubashrcstarts with the defaults.- Plugin activation is a derived plane, not an rc edit (niubash#359): the
manifest (
~/.niubash/plugins.json+~/.niubash/sources/registry.json) drives the generated loader~/.niubash/generated/plugins.niu, which the host sources read-only before the user rc. Noniu pluginverb writes~/.niubashrc. - Machine state — the plugin manifest, source registry state, the generated loader, test isolation, completion directories — is maintained by the internal managed-state mechanism and is not a user configuration entry point.
- Plain
niu -c, script files, and stdin scripts stay quiet and deterministic: no interactive rc, no generated loader, no source plugins.
The design principle is to minimize user-visible entry points: users edit
~/.niubashrc day to day; machine state is maintained by Niubash itself and
users never need to edit its storage format.
6. Plugin system
The built-in plugin/theme stack (and the oh-my-niu bundle format) is
retired (niubash#145): the plugin verbs hard-bail on bundles, and release
packages stage no plugin content (niubash#161). The plugin system is the
external bash ecosystem as first-class content.
- Sources are real upstream projects — oh-my-bash, bash-it,
bash-completion, any wild plugin repo or single file — installed over
git clone on explicit user command (
niu plugin add), never vendored into the product. - Sources activate only through an explicit
niu plugin enable; framework assets enable through each manager's own selection mechanism (rc arrays,enabled/entries), never through shims that re-implement upstream library functions. - The declarative spec
~/.niubash/plugins.jsonis the source of truth for what is declared; the registry pins installed trees (commit), andniu plugin syncreconciles the two. - Plugins cannot extend the rubash parser/executor, and cannot source
arbitrary legacy
.winshfiles or rc fragments found in user directories beyond what the enabled sources themselves declare. - Editor capabilities come from ruline and Niubash-native keybinding presets.
Repository layout
niubash/
├── Cargo.toml
├── LICENSE # MIT
├── README.md / README-zh.md
├── .niubashrc # primary interactive user entry (~/)
├── managed state # internal machine-managed state (~/.niubash/)
├── crates/
│ └── niubash-runtime/
│ ├── Cargo.toml
│ └── src/
│ ├── lib.rs # library entry
│ ├── shell.rs # shell state
│ ├── repl.rs # ruline REPL
│ ├── ctrl_c.rs # Win32 Ctrl+C
│ ├── config.rs # config parsing
│ ├── winuxcmd.rs # winuxcmd discovery
│ ├── prompt.rs # prompt rendering (floor)
│ ├── prompt_segments.rs # segment presets
│ └── completion/ # completion system
├── src/
│ └── main.rs # binary entry
└── docs/
├── src/
│ └── (this documentation book)
└── planning/
6. In-process readline C ABI (niubash#775, ruline#8)
GNU readline is not a separate library inside niu: the editor is ruline
(the house GNU-readline-compatible editor; the crate still carries
the reedline package name during the rename, ruline#9) compiled
into the executable. Bash loadable builtins
(enable -f ./mybuiltin.so mybuiltin) are dlopened into that process, so
their rl_* / history_* references must resolve against niu's main
executable — the live editor — rather than against a second readline
instance.
The ABI definitions live in the ruline readline-abi crate
(https://github.com/unixwin/ruline/issues/8), pinned as a git dependency
of the root niu package. Its lib target is named readline
(readline_abi is the package name); src/main.rs calls rl_initialize()
once at startup so the exported globals (rl_line_buffer, keymaps, funmaps,
completion defaults) exist before any plugin can load. The host does not
implement rl_* itself: readline(), history, keymaps, funmaps, hooks and
completion belong to the ABI crate.
The exported set is checked in at scripts/readline-abi-exports.txt
(one F <name> / D <name> per line, generated from the built
libreadline with scripts/gen-readline-abi-exports.sh). Publishing it
needs a per-platform link switch, done in build.rs for the niu binary
only (the bash binary re-execs niu and never hosts an editor):
| Target | Flag | Why |
|---|---|---|
| ELF (Linux, Android/Termux, musl) | -rdynamic (--export-dynamic) | Adds global definitions to the dynamic symbol table so dlopen resolves them. |
| Mach-O (macOS) | -Wl,-export_dynamic | ld64's documented "main executable may load a plug-in" switch; -rdynamic is not an ld64 option. |
| Windows MSVC | /DEF:<generated .def> | link.exe exports nothing by default; a curated EXPORTS list is the MSVC equivalent and avoids publishing every Rust internal. |
| Windows MinGW | <generated .def> | GNU ld/lld take the same curated EXPORTS list as a link input; --export-all-symbols was dropped in niubash#999 after the export table passed the PE 16-bit ordinal limit (65535). |
A static ELF build (the *-unknown-linux-musl default) has no dynamic symbol
table and cannot load shared objects, so build.rs skips export setup for
crt-static targets; those builds use the standalone libreadline.so.8
embedding mode instead.
Visibility is not retention: a definition in an rlib member is only linked
when something references it, and plugins reach the ABI through dlsym, not
through Rust code. Every name in the checked-in list is therefore also
anchored as undefined (-Wl,--undefined=<sym>, -Wl,-u,_<sym>,
/INCLUDE:<sym>) so its member is pulled into the link even under thin LTO
and --gc-sections. MSVC's generated .def marks data symbols with DATA
and leaves functions bare.
tests/readline_abi_exports.rs audits the entire list against the built
binary (nm -D / readelf --dyn-syms, dumpbin /exports on Windows), with
a second focused test for the symbols the loadable-builtin-niu plugin
probe resolves; scripts/check-readline-abi-exports.sh runs the same audit
on release artifacts.
Two embedding modes are supported, and only one shares niu's editor:
- Host mode (this executable) — loadable builtins resolve the symbols
above from running niu. Today the ABI crate owns a standalone editor
state that
rl_initialize()sets up; routing it to the live ruline editor (rl_line_buffermirroring,rl_*edits landing in the prompt) is the remaining follow-up. - Standalone
libreadline.so.8/libhistory.so.8— the ruline ABI crate'scdylib; an external embedder that links it owns its own editor instance and does not see niu's process state.
bind -x (engine bindings applied to the editor through the __niu_bindx
host command), __niu_readline host commands, READLINE_* read-back and
inputrc handling keep their existing paths; the ABI export changes no
behaviour until the live routing lands.
Data flow
user types "ls -la | grep foo"
│
▼
ruline (line editing + completion)
│
▼
shell.execute_line(line) ← niubash-runtime
│
├─ rubash::lexer::tokenize(line)
├─ rubash::parser::parse(tokens) → Ast
└─ executor.execute_ast(&ast) ← rubash owns all semantics
│
├─ built-ins (cd/source/echo...)
├─ external command → find_user_command("ls")
│ │ (PATH already carries the winuxcmd dir)
│ ▼
│ winuxcmd.exe ls -la
│
├─ pipeline: | grep foo → find_user_command("grep")
└─ output to stdout
Differences from the old architecture
| Aspect | v1 (old niubash) | v2 (current niubash) |
|---|---|---|
| Shell engine | in-house winsh lexer/parser/ast | rubash lib |
| Coreutils | winuxcmd FFI (DLL, disabled) | winuxcmd.exe process (PATH injection) |
| Command routing | command_router.rs classification table | rubash-internal find_user_command |
| Built-ins | self-implemented builtins.rs | rubash::builtins |
| Completion | src/completion/ | fully preserved, migrated |
| Themes | theme.rs (8 themes) | built-in stack retired (niubash#145); themes come from external sources |
| Plugins | Plugin trait + Oh-My-Niubash | external bash ecosystem as sources (add/enable; no bundles) |
| License | MIT | MIT |
Version planning
- v2.2: stabilize the rubash rewrite, completion enhancements, Vi mode and Ctrl+R, configuration consistency, user themes
- v2.3: Windows-native terminal contract, agent-friendly non-interactive behavior, history/prompt/completion UX
- v2.4: interactive polish (right prompt, hints, completion menu, defaults)
- v3: the external-ecosystem plugin system — first-party packs replaced by
real upstream sources (oh-my-bash, bash-it, bash-completion, wild
plugins); the
oh-my-niubundle format was retired along the way (niubash#145/#161). Activation moved off the user rc in 1.4.2: the manifest drives a generated loader at~/.niubash/generated/plugins.niu(niubash#359). - Shipping beyond Windows is no longer a non-goal: Linux and macOS portable builds are released and smoke-gated beside the Windows installer (see Platform Support); Android and OpenHarmony remain incubating CI targets.
Last updated: 2026-10-22
Windows Path Contract
Niubash uses a real Windows directory tree for its Unix-shaped shell paths. This is path spelling support, not MSYS, WSL, Cygwin, a POSIX runtime, or a filesystem overlay.
Ownership
| Layer | Responsibility |
|---|---|
| Niubash | Select one winuxcmd.exe, derive its installation root, create the real tree, and configure the shell session. |
| Rubash | Interpret /, /bin, /usr/bin, /etc, /tmp, cd, source, glob, redirects, tests, and command lookup. |
| WinuxCmd | Implement external commands and native Windows filesystem, process, handle, and device operations. |
| WPM | Install package payloads and command links inside the selected installation root. |
Installation Root
For an installed executable such as:
C:/Users/Administrator/AppData/Local/Programs/Niubash/winuxcmd/usr/bin/winuxcmd.exe
the shell root is:
C:/Users/Administrator/AppData/Local/Programs/Niubash/winuxcmd/
usr/bin/
bin/
usr/local/bin/
etc/
var/
dev/
.wpm/
These are ordinary Windows directories. usr/bin is canonical for
winuxcmd.exe, wpm.exe, command links, and filename-only WPM targets.
Explicit WPM targets under bin, usr/bin, or usr/local/bin remain in that
exact directory. .wpm is private package state and is never a command path.
Niubash passes this exact root to Rubash as NIU_ROOT. It is both the
session's root (Rubash records it as __RUBASH_SHELL_ROOT) and a real
process-environment variable, because the bundled WinuxCmd applets resolve the
shell-tree spellings through their own shell_ns::root and therefore read the
child environment (unixwin/niubash#746). Rubash maps paths lexically below it:
/ -> <root>
/usr/bin/tool -> <root>/usr/bin/tool
/bin/tool -> <root>/bin/tool
/etc/config -> <root>/etc/config
/tmp is deliberately NOT part of this tree: it is a per-user temporary
namespace resolved to the real Windows temp directory (TMPDIR, else
%TEMP%), so it stays writable under any install location
(unixwin/niubash#94). /var/tmp resolves beside it as
<real temp>/var/tmp. For every child that is not a bundled WinuxCmd applet,
external command arguments are translated by the Rubash executor with the same
rules — including /mnt/X drive spellings — so there is
exactly one path-semantics owner and no host-side AST rewrite. Device spellings
are not part of that set either, and they split by spelling and child class
(see Special Paths): the exact /dev/null token is rewritten for native
children only, while the fd-bound spellings (/dev/stdin, /dev/fd/N) reach
every child verbatim. One child class is exempt from the drive-form rewrite,
described under Shell Namespace Ownership.
Command lookup and native child PATH use these real directories directly.
Rubash does not merge a second provider directory, and WinuxCmd applets read no
Niubash configuration — only the root published as NIU_ROOT (see Shell
Namespace Ownership). Existing flat installations remain usable when
their directory is explicitly present on PATH; new installs use the tree
above.
Shell Namespace Ownership
A child process either resolves the shell namespace itself or receives native paths — never both, and never a guess about the child's capabilities:
-
Bundled WinuxCmd applets own the shell tree (unixwin/niubash#346). The applets selected by the dispatcher route, the configured root, and the
winuxcmd.exetree marker receive/,/usr/bin,/etc,/tmp,/home,/mnt/X, the bare/, and/dev/*VERBATIM, and resolve them through WinuxCmd's own shell-tree layer, which mirrors Rubash's root map. They therefore render the POSIX face (ls -d /usr/bin,realpath /etc,readlink -f /tmp) and stay consistent with the spelling-preservingpwd. The executable-leaf convention is theirs too:/usr/bin/seqresolves to the realseq.exewhilels -dkeeps the operand spelling, sohead -1 /usr/bin/seqandtest -f /usr/bin/seqagree (niubash#177). -
Every other child — a native Windows program, or a foreign POSIX runtime such as MSYS2 or Cygwin — receives native Windows paths. There is no per-child capability probe and no
MSYS_NO_PATHCONV-style switch; a foreign runtime is treated exactly like a native program. -
The bare
/is the one operand that second class does not receive translated (unixwin/niubash#153, niubash#748)./usr/bin,/etc,/tmp, and/mnt/Xare unambiguously path-shaped, so Rubash translates them for native children; a lone/is also a data operand —expr 10 / 3,tr / X,grep / file— and only the child's grammar can tell the two apart. Rubash therefore hands the bare/over verbatim, and a native child resolves it by its own semantics (on Win32, the current drive's root). Bundled applets still receive it verbatim and map it through WinuxCmd's shell tree, and the grammar mask keeps the data positions ofexpr,tr,grep,sed,awk,find,basename, anddirnameverbatim. Consequence:ls.exe /(applet) is the shell root, whileeza /(a native program) is the current drive root. That is the boundary, not a bug; niubash#748 records the decision to keep it rather than add aNO_CONV-style switch. -
Drive-root forms —
/dand/d/— are handed verbatim to native children too (niubash#779). With-components forms such as/d/repotranslate unconditionally, but the bare root form is also a switch spelling in native grammars:/cis both the C-drive root andcmd.exe's run-and-exit switch, andxcopy /Dandrobocopy /Ehave the same collision. No boundary rule can tell the two apart — an existence test cannot help, because a drive root always exists — so the root forms stay as typed and the child resolves them by its own (Win32, drive-relative) semantics. That is the boundary, not a bug; niubash#779 records the experiment corpus behind the decision, and it applies to every drive uniformly (a former drive-C exception, which also mistranslated data such astr '/c/' X, was removed by the same ruling). To name a drive root for a native program, spell it/d/.,/mnt/d/, orD:/— all three reach the drive root today. -
One exception, and it is not a capability probe:
cmd.exe. A single-letter drive form such as/d/repoor/c/Usersreachescmd.exeverbatim, because/dand/care indistinguishable fromcmd's own switches. Root forms and/mnt/Xspellings are still translated, socmd /c echo /usr/binandcmd /c echo /mnt/c/Usersarrive native whilecmd /c echo /d/repodoes not. The exemption is pinned in Rubash (is_windows_command_processor, and thewindows_cmd_switches_are_not_mapped_into_shell_roottest) and applies tocmd.exealone: a native program that is notcmdreceives/d/repoasD:\repo. -
The MSYS escape spelling
//xis not folded anywhere,cmdincluded (niubash#993 §2).//is MSYS2's own quoting convention: its runtime rewrites a leading//xinto/xprecisely because its own argument conversion would otherwise mangle/xinto a drive path. niu has no such conversion to escape, so a doubled slash reaches the child as typed.cmd //c "echo hi"therefore hands cmd.exe the literal word//c, which cmd does not recognise as a switch, and cmd opens an interactive session — the failure mode is a prompt waiting on stdin (a hang in a script, a stray prompt in a terminal), not an error message and not a nonzero exit. The correct spelling is the one MSYS made fragile:cmd /c "echo hi"works as written, because the cmd.exe exemption above already keeps/cverbatim. A targeted//x→/xfold for single-letter switches of command processors (the gash PR #11 approach) remains an open option; nothing is folded today. -
Namespace bridges stand outside the translation boundary entirely:
wsland the OpenSSH client family (ssh,scp,sftp). Their arguments are not paths on this machine at all — they are interpreted inside another filesystem namespace (a WSL guest's tree, an SSH remote's tree) — so the Rubash executor hands every argument to them byte-for-byte verbatim: no root map, no home/temp map, no drive-form rewrite, no/dev/nullrewrite. Membership in the class is the platform property of being a namespace bridge; the set is the platform's fixed bridges, pinned in Rubash (is_namespace_bridge_programand thepathmatrix_bridge_*tests). A bridge's remote words therefore survive exactly as typed:ssh host cat /var/log/xandwsl cat /home/user/filename the remote/guest files the user spelled, never local ones. -
The bridge's verbatim rule reaches its local-path operands too, so Windows OpenSSH needs native spellings for them (niubash#993 §9).
ssh/scp/sftp/ssh-keygenresolve to the Windows OpenSSH port, which has no MSYS virtual filesystem:ssh -i /c/Users/x/.ssh/key,ssh -F /c/…, the local side of anscp/sftptransfer,ssh-keygen -f /c/…, andIdentityFile/Includelines inside~/.ssh/configmust spell local files in theC:/…(orC:\…) form. A/c/…operand arrives verbatim and fails asWarning: Identity file /c/… not accessible— Git Bash survives the same spelling only because its ssh is an MSYS build that resolves/c/in-process. Remote-path operands are unaffected: inscp local.txt host:/tmp/the remote half still spells the remote tree POSIX-style, which is the namespace that word lives in. (A separate upstream face of the same client family is tracked at PowerShell/Win32-OpenSSH#2478, thessh -tpty branch.) -
Environment variable values follow the same boundary (niubash#1001, rubash#4154). When the shell spawns a child of the second class (a native Windows program, or a foreign POSIX runtime), an exported value that is a path-dialect spelling —
/d/repo, or a colon-separated list of such spellings — is folded to native form (D:\repo; list entries join with;), exactly like an argv operand. Every other value — URLs, relative spellings, non-path data — reaches the child byte-for-byte, and the contract-verbatim variables (PWD,OLDPWD,PATH,TMPDIR,__RUBASH_*) are never folded. A user who needs a path-shaped value delivered verbatim names the variable in__RUBASH_ENV_CONV_EXCL: a;-separated list of variable-name prefixes (*exempts every variable; a trailing=means the exact name). The MSYS2 conversion variable names (MSYS2_ENV_CONV_EXCL,MSYS2_ARG_CONV_EXCL,MSYS_NO_PATHCONV) are not honored: niu has no MSYS conversion layer for a variable to switch off.
The boundary is structural rather than a rename of the "MSYS NO CONV" problem: the shell never asks a child what it can understand. The shipped toolchain's own resolution decides, and the engine compensates only for the child classes that cannot resolve the tree.
User-space trade-off
A user who prefers a native tool (for example eza) over a bundled applet
accepts native path semantics for it, including the lone-/ rule above.
The shell does not rewrite argv to make that tool look POSIX, and no
environment variable turns such a rewrite on. If you want only the common
single-operand ls / spelling to show the shell root, opt in in
~/.niubashrc with a user-owned wrapper (remove any existing alias ls=…
first: an alias wins over a function of the same name):
# ~/.niubashrc — user-space opt-in, NOT part of the shell contract.
# eza is a native Win32 program: a lone "/" is the current drive root.
# This makes only `ls /` (one operand) resolve to the shell root.
ls() {
if [ "$#" -eq 1 ] && [ "$1" = "/" ]; then
command eza -- "$NIU_ROOT"
else
command eza -- "$@"
fi
}
The wrapper is deliberately narrow: eza / called directly, multi-operand
forms such as ls / /usr, and every other native program keep the native
meaning. For POSIX spelling everywhere, use the bundled applets (ls,
find, realpath, …) rather than a native replacement. If your rc already
contains an alias ls=eza line (for example from the setup wizard's
optional eza recommendation, which only appears when you have eza on
PATH), remove that alias before defining the function; niu never rewrites
your rc.
Dispatcher Selection
WINUXCMD_PATH selects one exact dispatcher executable for the session.
Niubash resolves it, prepends that installation's usr/local/bin, usr/bin,
and bin directories to the native PATH, and passes the exact executable to
Rubash. Rubash does not discover another dispatcher from PATH.
The dispatcher is only a fallback when a command is absent from the real tree.
It must not implement Rubash builtins such as cd, export, set, read,
jobs, or trap.
Launcher Precedence (PATHEXT before POSIX)
When a directory on PATH holds both spellings of a tool — the POSIX
launcher bin/tool and the Windows launcher bin/tool.bat / bin/tool.cmd
(the standard pair SDKMAN candidates, Gradle, and Maven ship) — a bare name
resolves to the .bat / .cmd launcher, not the POSIX script
(niubash#993 §12). command -v gradle reports the .bat path; type -a
lists both spellings. Git Bash resolves the same pair to the POSIX script,
so the two shells run different launcher code for the same tool: different
JAVA_HOME probing and GRADLE_OPTS/JAVA_OPTS quoting through cmd.exe,
and a different JAVA_HOME string for the same JDK when the launcher derives
it (the .bat reports the C:/… form, the POSIX script the /c/… form).
The .bat wins deliberately: it needs no $0/dirname resolution, so the
$0-of-PATH-resolved-scripts failure class cannot reach the launcher — that
is why Gradle and Maven work here at all. The installation selection is
unaffected (both shells pick the same SDKMAN candidate or install dir); only
the launcher spelling differs.
Special Paths
~ is USERPROFILE, the same directory used by PowerShell. Windows paths
such as C:/work/file and /c/work/file remain host paths.
The only device spelling currently supported is /dev/null. As a redirect
target it is mapped to the native NUL endpoint. As an external-command
argument it depends on the child class (Shell Namespace Ownership above):
the bundled WinuxCmd applets receive it verbatim — /dev spellings are
shell-namespace arguments their own layer resolves — and the namespace
bridges receive it verbatim, since their words name files in another
namespace; a native child instead receives nul, because the POSIX
spelling names no Windows file it could open. The rewrite covers the
exact token, the value position of name=/dev/null, and the attached
short-option form -o/dev/null (rubash#1506). The other /dev entries
reach every child verbatim; they do not become ordinary files until
their fd or terminal capability is implemented.
tags: [niubash, platforms, unix, harmonyos] created: 2026-10-09 status: active
Platform Support
Which platforms Niubash runs on, what "runs" means for each, and the parts of the surface that are deliberately different per platform. This page is the contract; if a platform behaves differently from a claim here, that is a bug.
Status matrix
| Platform | Build | Smoke-gated | Released | Notes |
|---|---|---|---|---|
| Windows x64 | ✅ windows-2025 | ✅ release gate | ✅ .zip + .exe | primary target |
| Windows arm64 | ✅ windows-2025 | ✅ release gate | ✅ | |
| Linux x86_64 (glibc) | ✅ ubuntu-22.04 | ✅ release gate | ✅ .tar.gz | glibc ≥ 2.35 |
| Linux aarch64 (glibc) | ✅ ubuntu-22.04-arm | ✅ release gate | ✅ | native arm64 runner |
| macOS aarch64 | ✅ macos-latest | ✅ release gate | ✅ | |
| macOS x86_64 | ✅ macos-latest | ✅ (Rosetta 2) | ✅ | Apple cross-compile |
| Linux x86_64 (musl) | ✅ ubuntu-latest | ✅ cross-target-smoke | ⬜ | static; see below |
Android (aarch64-linux-android, armv7-linux-androideabi) | ✅ release build-android | ⬜ | ✅ .zip since v1.4.3 | NDK-linked zip, CI runs no runtime smoke; see below |
HarmonyOS PC (aarch64-linux-ohos) | ✅ ubuntu-latest check | ⬜ | ⬜ | see below |
"Smoke-gated" means the artifact is built, then run on its own OS, against
the four checks in release.md before it is published —
--version banner, -c execution, a pipeline through native coreutils,
and the offline plugin stack. No smoke, no artifact.
musl
Compiled by cross-target-check and smoke-tested by
cross-target-smoke, which builds the static musl binary and runs the same
four checks natively (a static musl x86_64 binary runs on the glibc
runner). The job asserts ldd reports statically linked first, so a
silent re-link against the runner's glibc cannot pass as a musl build. No
musl-tools package is needed: rustc links against the toolchain's own
self-contained musl crt/libc through the host cc.
No musl release artifact ships yet. That is a delivery decision, not a
coverage gap — flip it on by adding x86_64-unknown-linux-musl to the
build-linux matrix in release.yml.
Android
The build-android legs in release.yml build aarch64-linux-android and
armv7-linux-androideabi with a real bionic link through the NDK
(nttld/setup-ndk, API 24 clang drivers). The bionic cfg surface was fixed
upstream in rubash#456 (AT_EACCESS, confstr, sa_restorer, 32-bit
off_t/S_IFMT widths). The legs are incubating: continue-on-error, not
in the release needs — the runner cannot execute bionic binaries, so the
four-check smoke gate has not run for these in CI. Since v1.4.3 the zips
still ship on the GitHub Release page (niubash-v1.4.3-android-aarch64.zip
and -armv7.zip), and the aarch64 zip runs on real hardware: smoke-checked
on a Termux aarch64 device (--version, -c execution, a pipeline through
sort). Build-verified in CI, run-verified on one real device — not yet
gate-verified.
The leg does carry a measured performance baseline on real hardware
(Termux aarch64, niubash 1.4.0 vs GNU bash 5.3.20):
niubash#352 — interpreter-bound
workloads 2.3–3.7x slower (up to 7.3x on ${x^^}), niu -c true 21.1 ms vs
8.3 ms, peak RSS 2.2x, while fork-bound workloads run up to 5.2x faster and a
real mkdir/write/read-back script 2.1x faster. The attributed root causes are
all closed — engine interpreter triage (rubash#607-609) and the one-shot
wrapper gap (niubash#351:
niu -c true 15 ms vs bash 13 ms after the fix, zero tput spawns) — but no
post-fix re-measure on device exists yet; #352 stays open for it. The full
table and the Windows-side numbers live in
Performance.
HarmonyOS
The Rust target is aarch64-unknown-linux-ohos. Two facts make it mostly
free:
rustc --print cfg --target aarch64-unknown-linux-ohosreportstarget_os = "linux"andtarget_family = "unix". So Niubash's existing unix leg and rubash's existing Linux leg apply nearly unchanged, andfd/mod.rs's#[cfg(unix)]arm is taken as-is.- The target is Tier 2 with host tools in Rust, so a check-only build needs no external OpenHarmony SDK or clang wrapper.
The one compile blocker found so far was rubash's ulimit, which typed its
resource selector as libc::__rlimit_resource_t — a typedef only glibc
defines. musl and the OpenHarmony libc take a plain c_int. Fixed by
aliasing on target_env (rubash#449). With that, the whole Niubash
workspace compiles for aarch64-unknown-linux-ohos.
cross-target-check (in ci.yml) keeps it compiling. It is check-only
because there is no HarmonyOS runtime available on GitHub runners, so the
gate is "it compiles", not "it runs" — the ohos column of the status matrix
stays ⬜ until a real device runs the smoke gate.
What HarmonyOS PC actually ships
An earlier revision of this page described HarmonyOS as "a de-GNU'd Linux
distribution — musl libc, mksh as the default shell, toybox built in".
That is wrong for HarmonyOS PC. It came from OpenHarmony's dev-board
userland and was applied to the whole platform. The two are different
products and the difference changes how much Niubash has to supply.
HarmonyOS PC is not stripped down. A measured install (HarmonyOS
1.12.0, aarch64, kernel HongMeng Kernel 1.12.0) runs bash as the
shell (/data/service/hnp/bin/bash) and carries 454 commands under
/data/service/hnp/bin — about 93% of a standard Linux command
surface, and 100% of text processing:
grep sed awk cut sort uniq diff diff3 comm cmp head tail wc fold column
Also present: clang/gcc (multi-arch: aarch64 / armv7 / loongarch64 /
x86_64), cmake, make, ninja, autoconf, bison, flex, gdb,
lldb, git (+ git-lfs, git-svn), python3.12, node, full JDK,
ruby, vim/nvim/nano. What is genuinely missing is system
management, not text processing:
| Missing / restricted | Note |
|---|---|
apt / yum / dnf | no classic package manager; use hnpcli or preinstalled |
systemctl | no systemd; HarmonyOS has its own service management |
iptables / nftables | restricted |
docker | not preinstalled |
snap / flatpak | unsupported |
ifconfig / netstat | present but partly restricted (ip, ss preferred) |
The HarmonyOS bash is stock GNU bash
It is worth pinning down what that bash is, because "it has bash" could mean a reimplementation. It is not. It is upstream GNU bash, cross-compiled against musl:
bash --versionon a HarmonyOS PC printsGNU bash, version 5.1.16(1)-release— the GPL banner is GNU's own.- The public HNP build (Termony,
build-hnp/bash/Makefile) pulls$(GNU_MIRROR)/gnu/bash/bash-5.3.tar.gzand configures it with--host aarch64-unknown-linux-musl --without-bash-malloc --disable-nls.--without-bash-mallocmatters: it drops bash's bundled allocator so the musl allocator is used instead. - The build emits
libsh.a,libhistory.aand theloadables(recho,printf,basename, …) — artifacts unique to the GNU bash source tree.
No Huawei-specific shell patches. It is an ordinary musl-linked GNU
bash, which is a useful data point for us: the userland under HarmonyOS is
a musl + Linux-ABI stack, not a bespoke one. That is why Niubash's
target_os = "linux" cfgs all hit and why the port was two lines.
Note the version split when quoting numbers: the measured machine ran 5.1.16, while the public build recipe fetches 5.3. These are different devices at different times — do not present either as "the" HarmonyOS bash version.
Two userland caveats the existing ports hit
Both are worth knowing before a first device run, because neither is a documentation problem — they are things that actually broke people.
1. A third-party port still needed to bundle a shell toolset.
Termony (a "Termux for HarmonyOS PC") ships 42 packages, and its list is
aria2 bash binutils *busybox* ... gcc gdb gettext git ... — bash yes,
coreutils no, busybox instead. So even with 454 commands present system-
wide, an independent porter concluded the stock surface was not enough and
vendored busybox to fill it. That is not proof the 93% number is wrong;
it is evidence that "the tools exist" and "the tools are dependable" are
different claims — the same distinction the argument below turns on.
2. Prefix mismatch inside the built-in Terminal. Termony's README warns:
you can use these utilities in the builtin Terminal app under
/data/service/hnp: Although some paths might get wrong due to prefix set to/data/app/base.org/base_1.0… You can override them like:LD_LIBRARY_PATH=/data/service/hnp/base.org/base_1.0/lib TERMINFO=/data/service/hnp/base.org/base_1.0/share/terminfo fish
This does not contradict the PATH finding below — PATH resolution and
runtime prefix resolution are separate mechanisms. It does mean that a
first device run should check more than "is it on PATH": also confirm that
a resolved binary can actually find its own lib and data dirs. On
HarmonyOS 6.0+ the README adds that sudo is available and system
environment variables are editable, which is how the overrides are meant
to be persisted.
The OpenHarmony dev boards are the limited case
There the userland is toybox, and Huawei's own documentation says it is
trimmed per device:
In the current version, different devices support different toybox commands. You can run the
toyboxcommand to obtain the full list.
Community reports go further: toybox: Unknown command diff even though
diff.c exists in third_party/toybox/toys/pending and is listed in
BUILD.gn. The workaround people use is "选择使用 busybox 代替 toybox".
The third-party pkgsrc bootstrap lists gawk and grep as required
dependencies, which implies they are absent by default.
The honest split:
| HarmonyOS PC | OpenHarmony dev boards | |
|---|---|---|
| Shell | bash | mksh |
| Command set | 454 commands at /data/service/hnp/bin (~93%) | toybox, per-device trimmed |
| Text processing | fully covered | gaps; awk/grep absent, diff may be "unknown" though the source exists |
| What Niubash adds | a consistent bash + GNU-toolset baseline across OS versions, plus the Bash semantics | the missing tools, not just the semantics |
State the argument plainly, because it changed: on HarmonyOS PC the value is not "the commands are missing". It is that the toolset is not guaranteed uniform across device revisions, and that a bash-compatible runtime is still what you want when you do not control the host. Both are real, but weaker than "there is nothing here", and this page should not overstate them.
Packaging: HarmonyOS PC requires HNP
HarmonyOS PC does not accept the tarball layout the Linux legs ship. The constraint is documented for native ports and it is absolute:
在鸿蒙PC上,由于系统安全规格限制等原因,暂不支持通过"解压 + 配 PATH"的方式直接使用 tar.gz 包 ❌ 不能直接解压 tar.gz 包到任意目录 ❌ 不能通过设置 PATH 环境变量来使用 ✅ 必须打包成 HNP(HarmonyOS Native Package)格式才能正常使用
HNP = HarmonyOS Native Package, the platform's native package format —
the analogue of MSI on Windows or deb/rpm on Linux. Packed with hnpcli
(which ships in the OpenHarmony SDK):
hnpcli pack -i <pkg-dir> [-o <out-dir>] # with hnp.json present
hnpcli pack -i <pkg-dir> -o <out-dir> -n <name> -v <ver> # without
The payload is a directory with bin/, optional cfg/ and lib/, and a
required hnp.json:
{
"type": "hnp-config",
"name": "hnpsample",
"version": "1.1",
"install": {
"links": [
{ "source": "/bin/hnpsample", "target": "hnpsample" }
]
}
}
source is relative to the package root and target becomes a symlink
name in the bin directory. If links is omitted, every binary under
bin/ gets a symlink by default. Constraints: no spaces or special
characters in name/version, no non-ASCII directory names, package
≤ 4 GB. Binaries that need their own libraries should carry an rpath
(-Wl,-rpath=${ORIGIN}/../lib).
The distribution path is the part that matters. An .hnp is not
installed standalone. It is embedded in a HAP — an app bundle —
declared in module.json5 as hnpPackages with "type": "public" or
"private", and the HAP is signed and distributed through AppGallery:
HAP project root
└── hnp/ # hnp root, as passed to --hnp-path
└── arm64-v8a/ # device ABI dir
├── python.hnp
└── sub_dir/test.hnp
So shipping Niubash to HarmonyOS PC is not "publish a .hnp and let
people install it". It means publishing a HAP on the app store whose
payload is Niubash's binaries. That is an app-store listing, a signature,
and a review — the same shape of gate as the phone form factor, just with
a looser runtime policy. Anyone who thought "HarmonyOS PC is a tarball"
should recalibrate: the packaging is cheap, the distribution is a
store release.
A public build framework exists —
gitcode.com/OpenHarmonyPCDeveloper/build
— which cross-compiles Linux/Unix CLI tools to aarch64-linux-ohos and
packs them as HNP; it consumes OHOS_SDK, drives everything through
build.sh --sdk <path>, and registers components in a dependency.json.
Precedent components include tree and ninja.
The "same shape as the Linux leg" claim was wrong, twice over: the
artifact is different (niu-<ver>-ohos.hnp, inside a HAP), and the
delivery channel is different (store, not direct download).
Where HNP installs, and whether it lands on PATH
Two install roots, both of which do put their bin on PATH:
| Kind | Install path | Binaries symlinked into | On PATH? |
|---|---|---|---|
| Public HNP | /data/service/hnp/<name>_<version>/ (HNP_PUBLIC_HOME=/data/service/hnp) | /data/service/hnp/bin | ✅ yes |
| Private HNP | /data/app/<name>_<version>/ (HNP_PRIVATE_HOME=/data/app) | /data/app/bin | ✅ yes |
The official guide is explicit: "公有hnp包二进制软链接路径:/data/service/hnp/bin(已加入环境变量)", and the same for
/data/app/bin. Where the two collide, HNP_PRIVATE_HOME wins — a
same-named private binary shadows the public one.
So the open question from the previous revision is closed: a HNP does
put its commands on PATH, and /data/service/hnp/bin — the same
directory the 454-command measurement counted — is that symlink
directory. Tools that install and then say "安装后找不到 ninja 命令?" and
ask you to export PATH=... by hand have gone a manual route; that is not
what the packaging system does by itself.
This is good news for Niubash: no Unix command-directory discovery
mechanism is needed. Once the HAP is installed, the host looks like any
other Unix box and Niubash's existing PATH-based discovery works
unchanged. A real device should still run the smoke gate — but this
particular unknown does not need one.
The build-framework side still uses HNP_PUBLIC_PATH when cross-compiling
on a dev host (e.g. export HNP_PUBLIC_PATH=~/HarmonyOSPC/data/service/hnp)
so hnpcli writes into the right tree; that is a build-host variable, not a
runtime one.
uname on HarmonyOS
uname/arch do not hard-code a platform name. On unix,
crates-side identity.rs reads uname(2) and prints utsname verbatim,
the same way coreutils uname(1) does. So the reported values are whatever
the running kernel says. Measured on real devices:
| Field | Flag | OpenHarmony (Linux kernel) | HarmonyOS (Huawei kernel) |
|---|---|---|---|
| sysname | -s | Linux | HarmonyOS |
| nodename | -n | the host name | the host name |
| release | -r | the kernel release | HongMeng Kernel 1.13.0 |
| version | -v | the build stamp | #1 SMP Sat Aug 15 11:19:26 UTC 2026 |
| machine | -m | aarch64 | aarch64 |
-s being HarmonyOS (not Linux) is the one that bites. config.guess
did not know it, fell through to "unable to guess system type", and
exited non-zero — which breaks every autoconf-based configure, including
LLVM's GetHostTriple.cmake. A patch proposing aarch64-unknown-linux-ohos
for uname -s = HarmonyOS was filed upstream in 2026-08.
-r is a string with spaces. Code that splices uname -r into a
compiler flag without quoting produces -D__HarmonyOS_HongMeng Kernel 1_12_0, which the shell splits into several arguments and Kernel is
mistaken for an input file. That is a real bug in the wild (BitMagic
7.13.4), and the fix was to override the platform label, not to change the
kernel.
There is nothing to special-case in Niubash, and that is deliberate: the
honest source is the kernel, not a compile-time constant. Do not add a
HarmonyOS-specific sysname() branch unless a concrete consumer needs
it — and if something does need to branch, it should match HarmonyOS
exactly, not Linux.
$BASH_VERSION reports Niubash's Bash-compatibility level (e.g.
5.3.0(1)-release) on every platform, HarmonyOS included.
Sandbox quirks worth knowing on HarmonyOS
Beyond the kernel name, HarmonyOS restricts the filesystem in ways a
portable shell has to survive. Measured on HarmonyOS 7 (aarch64):
/tmp is read-only and $HOME is not writable, so a probe that opens a
temp file gets Permission denied. That is why a naive config.guess
fails twice on the same box — once on the temp file, and again on the
unrecognised OS name. Applications also face binary code-signing
verification, which is why third-party executables on HarmonyOS PC
frequently hit Permission denied on launch.
A shell that assumes a writable $TMPDIR or a writable $HOME will
misbehave here. Niubash should be checked against both on the first real
device run; nothing in the build changes.
None of this changes the build. It is listed here so nobody spends a day re-deriving it.
HarmonyOS PC vs HarmonyOS phone
These are two different products, not one port.
| HarmonyOS PC | HarmonyOS phone | |
|---|---|---|
| Userland | full (bash + 454 commands) | full |
fork/exec of new processes | unrestricted | restricted — ordinary apps cannot create processes directly; the app must declare each one in its config and pass per-process review at listing time |
| Packaging | HNP (tarball + PATH is not supported) | HNP, same format |
| Distribution | HAP on AppGallery — an HNP is embedded in a HAP, not installed standalone | HAP on AppGallery |
| Status | the target this page describes | a new form factor; not in scope yet |
The fork restriction is the load-bearing runtime difference. Huawei's
own FAQ (faqs-ability-112) states that on phones the system restricts and
manages fork for ordinary apps, and community reports add that PC does
not restrict it. Niubash is built on a fork+exec model on unix (see
rubash's fd/unix.rs: Command::new + Stdio::from_raw_fd +
pre_exec), so PC is a plain port while the phone form factor needs the
process-declaration path to be sustainable before it is worth building.
But note what the distribution column now says: both are HAP. The packaging and store-release work is largely the same for the two form factors; what differs is the runtime process policy. That is a different split from the earlier "PC is a tarball / phone is an app" framing, and it is the accurate one.
Do not treat "HarmonyOS support" as one item. The store-release work is shared, but the phone form factor adds a per-process declaration and review gate that PC does not — and that gate is not something Niubash controls.
What niu is not: no MSYS runtime
On Windows niu prints MSYS labels: uname -s reports MSYS_NT-…,
$OSTYPE is msys, $MACHTYPE is x86_64-pc-msys. Those labels are a
compatibility persona (rubash#154),
not a runtime. Ecosystem scripts routinely gate on uname -s matching
MINGW*|MSYS*|CYGWIN* or on OSTYPE = msys before they run; the persona
exists so those gates open. It is a default, not a fact —
RUBASH_IDENTITY=native switches the builtins to the native face
(uname -s → Windows_NT, $MACHTYPE → x86_64-pc-windows).
Under the labels there is no MSYS2 runtime: no msys-2.0.dll, no
cygwin1.dll, and nothing inside a child process that converts POSIX argv
for Windows. niu is a pure native Windows build; every process it starts
is an ordinary Win32 process, and the POSIX-form argv an MSYS runtime
would rewrite in-child is instead rewritten by niu's own executor before
that process starts — the distinction the behavioral boundary below
states. So the uname story on this page splits by platform: on unix
the builtin reports the kernel verbatim (see
uname on HarmonyOS); on Windows it reports
persona labels that name a runtime which is not there.
The behavioral boundary (measured)
| A script written for real MSYS assumes | niu does |
|---|---|
| The runtime rewrites POSIX-form argv before a native child sees it. | It does — /c/Users/cmx reaches a native child as C:\Users\cmx (python -c 'import sys; print(sys.argv[1])' /c/Users/cmx). The exception is a native command processor: cmd /c echo /d/repo prints /d/repo, because cmd owns /C-style switches. |
/d/... reaches the child as D:\.... | For a native child, yes — git -C /d/repo/niubash rev-parse --show-toplevel prints D:/repo/niubash, and python -c 'import sys; print(sys.argv[1])' /d/repo prints D:\repo. A native command processor is again the exception (see above). |
An MSYS2 root: /etc/fstab, /etc/profile, MSYS2's /usr. | / is winuxcmd's installation root (ls / lists its usr, bin, etc, opt, …), not the current drive's root; the Unix-shaped /etc resolves inside that tree to a real Windows directory holding only winuxcmd's mtab shim. |
| MSYS2's bundled perl/awk runtimes. | No perl at all; awk is winuxcmd's own native build, not MSYS2's. |
The root row is the one that still bites: niu's / is the WinuxCmd
installation root, so a script that walks out from / sees the winuxcmd
tree (usr, bin, etc, opt, …) rather than a drive root, and there
is no MSYS2 /etc/profile or /etc/fstab. On the argv rows niu now
matches what an MSYS2-targeted script assumes: POSIX-form argv is
rewritten for native children, and shell-namespace roots such as
/usr/bin, /etc, and /tmp are mapped for every child class. The one
carve-out is the native command processor, which keeps its slash-prefixed
drive-form operands verbatim. Unlike an MSYS runtime, though, this is not
a layer inside the child: it is niu's own path handling, applied by the
Rubash executor at the child boundary and documented in the
Windows Path Contract (the internal
__RUBASH_ARGV_DIALECT=legacy switch restores the earlier
existence-gated behaviour).
One line of orientation: Git Bash = MSYS2 runtime + GNU bash; niu = native engine + compatibility persona. The labels match so ecosystem scripts run; the runtime they name is not present.
Audited drop-in deltas against Git Bash (niubash#993, ruled documentation — not bugs to fix):
uname -sreportsMSYS_NT-…, not Git Bash'sMINGW64_NT-…: niu is the MSYS-compatible persona, not a MINGW64 impersonation — theMSYS_NTlabel is niu's identity signature in agent shell detection. SettingMSYSTEM=MINGW64in the environment flips the prefix the same way it does under MSYS2.uname -rreports the OS version (10.0-…) rather than an MSYS-runtime release because no such runtime exists to version.git --versioncarries a.niugitsuffix on the bundled niu-git: the string is compiled into the niugit binary at packaging time (upstream of this repo), so there is nothing host-side to change — version parsers that gate ongit version x.y.z…should parse only up to the first non-numeric suffix segment.bind -llists GNU bash 5.3.20's own 176 readline functions; Git Bash's 177th entry is a Git-for-Windows patch artifact, not GNU.shoptlikewise rejectscompletion_strip_exe, a Cygwin/Git-for-Windows extension upstream bash has no option for.cmd //cis the MSYS escape spelling, and niu does not fold//: cmd.exe receives the literal//c, does not recognise it as a switch, and opens an interactive session — the failure mode is a hang (a prompt on stdin), not an error (niubash#993 §2). Writecmd /c, which works as typed: under Git Bash the bare/cis the fragile form (MSYS rewrites it toC:/), which is exactly why the//cescape exists there.ssh -i /c/…fails withWarning: Identity file /c/… not accessible: niu resolves the Windows OpenSSH port — no MSYS filesystem — andssh/scp/sftpare namespace bridges whose argv is passed verbatim, so a/c/…spelling for a local file never reaches one OpenSSH can open (niubash#993 §9). Spell local pathsC:/…— that covers-i,-F, the local side ofscp/sftp,ssh-keygen -f, andIdentityFile/Includein~/.ssh/config; remote-path operands keep their POSIX spelling by design. Git Bash survives/c/…because its ssh is an MSYS build that resolves the prefix in-process.
Calling PowerShell from niu
niu is a full bash, so every command string it runs (through
niu -c '...', a script file, or piped stdin) goes through expansion
first, and bash expands $ in double-quoted and unquoted text.
PowerShell uses $ for the same slot: $var, $args, $env:TEMP. Call
PowerShell without quoting discipline and niu expands PowerShell's
variables before PowerShell starts. An undefined niu variable expands to
the empty string, so this:
niu -c 'powershell -NoProfile -Command "$x=1; Write-Output x=$x"'
hands PowerShell =1; Write-Output x=, which fails with
=1 : The term '=1' is not recognized. $x was never a niu variable, so
bash replaced both occurrences with nothing.
This is standard bash semantics, not a quoting bug; the ruling and the reproduction cases are in niubash#203. The fix belongs to the calling side:
1. Escape the $. Inside double quotes, \$ survives expansion as a
literal dollar sign:
niu -c 'powershell -NoProfile -Command "\$x=1; Write-Output x=\$x"'
# prints x=1
It works, but every PowerShell $ now owes a backslash, and the one you
miss turns into an empty string; the error you get names the mangled
command, not the missing backslash.
2. Keep the $ inside bash single quotes. Bash never expands inside
single quotes. From an interactive niu prompt, one pair does the whole
job:
powershell -NoProfile -Command '$x=1; Write-Output x=$x'
Through niu -c the quoting doubles, because the -c payload is itself
a shell string to whatever shell launches niu. Once you are counting
backslashes at two levels, use the file route instead.
3. Write a .ps1 file and run it with -File (recommended). The
script's text never passes through bash, so nothing needs escaping. The
$t, $o, $env:TEMP case from #203's real-world report runs as
written:
niu -c 'powershell -NoProfile -ExecutionPolicy Bypass -File C:/scripts/scan.ps1'
-ExecutionPolicy Bypass is not optional polish. Windows clients ship
with the script execution policy set to Restricted, which refuses
.ps1 scripts with "running scripts is disabled on this system"; the
flag lifts that check for the one process and changes nothing outside
it.
The rule itself is bash's, not PowerShell's: any target that puts $ in
double-quoted or unquoted command text is subject to it.
What is Windows-only
By compile-time cfg, the following never appear on non-Windows paths and
must not be weakened (no wpm strings off Windows):
- WinuxCmd command links and the
wpmpackage-manager surface. - The ConPTY interactive journey harness.
- Windows path translation (
/mnt/Xdrive argv rewriting) and the Windows signal bridge.
Unix tarballs carry only niu + README.md + LICENSE; native system
tools are used as-is rather than bundled.
tags: [niubash, roadmap] created: 2026-07-13 status: active
Niubash Roadmap
Niubash is a Windows-native, non-isolated Bash-compatible shell for humans and agents.
niubash = rubash + winuxcmd + ruline + the external bash ecosystem
Done
rubashis embedded as the shell language engine, pinned to verified upstream commits (v1.4.3 vendors the Bash-5.3 patch-20 surface).- WinuxCmd command links provide bundled Unix-style commands through PATH.
- The REPL uses ruline for editing, history, menus, autosuggestions, syntax highlighting, vi/emacs modes, and prompt rendering.
~/.niubashrcis the primary interactive startup file — the only one on Windows; POSIX login shells additionally read the GNU profile chain first. The pre-rename legacy names and~/.bashrcare never read directly.- The plugin system is the external bash ecosystem: real sources
(oh-my-bash, bash-it, bash-completion, wild git repos) installed over
git clone, driven by the declarative manifest~/.niubash/plugins.json, and activated through the generated loader~/.niubash/generated/plugins.niu— no verb writes the user rc (niubash#359, v1.4.2). - Plugin inventory, review, doctor, enable/disable, update, and rollback
surfaces exist, plus a ~540-row recipe index and collections
(
niu plugin distro). - Git completions, Git prompt status, prompt templates, and p10-style segment presets are available.
- Host contract tests cover cwd, env, stdin, stdout/stderr, script args, command-mode parsing, and exit-code propagation.
- Released and smoke-gated beyond Windows: Linux (x86_64, aarch64) and macOS (aarch64, x86_64) portable builds ship beside the Windows installer.
Current Direction
- Keep shell semantics in
rubash; fix parser, executor, builtins, redirects, pipelines, functions, jobs, and Bash language behavior upstream. - Keep Windows host integration in Niubash: cwd/env synchronization, PATH injection, installer behavior, command links, prompt rendering, and REPL UX.
- Model the plugin system after mature shell frameworks: named packs in a bundle, pack manifests, sourceable helper files, exported aliases, completions, functions, hooks, prompt segments, keybindings, and themes.
- Keep prompt layout user/theme owned. Providers such as native Git status or Starship-backed Git supply segment data; they do not replace the whole prompt unless the selected theme chooses that layout.
- Keep third-party integration on reviewed sources and explicit process adapters until a real host API justifies another runtime.
Near-Term Work
- Grow the source coverage of the plugin ecosystem: more catalog managers, recipes, and collections riding the manifest + generated-loader plane.
- Land the remaining agent-facing installer paths named in
agents.md — persisted
SHELL,niu setup agents, and an accepted opt-in elevated task for the Git Bash convention slot. - Re-measure the Android baseline post-fix (niubash#352) and move the Android leg from build-verified toward smoke-gated.
- Split prompt responsibilities clearly:
- theme owns layout and connective text;
- prompt-core renders templates;
- Git/Starship providers supply data for
{git}and related tokens.
- File and fix WinuxCmd command issues separately from rubash language issues.
Verification
- Fast loop:
cargo fmt --check -p niubash; cargo build --locked; cargo test --workspace --locked - Runtime library:
cargo test -p niubash-runtime --lib --locked - Host contract: run the ignored host suites with WinuxCmd command links in PATH when changing PATH, cwd, env, or command-link behavior.
- Local Bash upstream gate remains local-only and should report 86 total, 86 passed, 0 failed for the Niubash binary under test.
Locked Decisions
- License: MIT.
rubashfollows latestunixwin/rubashmaster.- WinuxCmd stays integrated through PATH injection and command links.
~/.niubashrcis the normal user-authored interactive config — and the only rc file the shell reads (the GNU profile chain on POSIX login shells is a separate, honored surface, not an rc file).- Machine-managed state is not a human-authored configuration surface.
- The official plugin story is the upstream ecosystem itself — oh-my-bash, bash-it, bash-completion — installed on demand, never vendored into the product.