Skip to content

[compat] Differential probe battery: getopts stale-OPTIND breaks the shift $((OPTIND-1)) idiom; multi-negative-subscript expansions spam stderr; history dumps the user file under -c #614

Closed

Description

@caomengxuan666

Summary

Three bash-incompatible behaviors found by a differential probe battery (bash 5.3.20 vs niu 1.4.0, ~116 automated probes, 95 byte-identical / 13 name-only diffs / these). Each is reproducible with niu -c in isolation; the battery lives at ~/bench_niu/probes.sh (Termux aarch64).

1. getopts: stale OPTIND is not clamped — breaks the universal shift $((OPTIND-1)) helper idiom [the serious one]

When a getopts helper function is called a second time with fewer arguments than the first call, bash and niu diverge:

f(){ while getopts ":ab:" o; do case $o in a) echo got_a;; b) echo got_b=$OPTARG;; :) echo miss_$OPTARG;; \?) echo bad_$OPTARG;; esac; done; echo "after optind=$OPTIND"; shift $((OPTIND-1)); echo "rest=$*"; }
f -a -b X   # both: got_a, got_b=X, optind=4, rest=
f -z        # bash: optind=2  rest=     | niu: optind=4  rest=-z
f -b        # bash: optind=2  rest=     | niu: optind=4  rest=-b

Mechanism (isolated and confirmed): when getopts finds OPTIND > $# (stale from a previous call), bash clamps OPTIND to $#+1 for the new call; niu keeps the stale value, so the subsequent shift $((OPTIND-1)) (the idiom from bash's own manual, used by effectively every parse_args() helper) exceeds $#, fails silently (rc=1, no shift), and the unparsed flags remain in "$*" and get executed as positional arguments.

Per-call behavior is identical (f -z alone → bad_z, f -b alone → miss_b, OPTIND persistence across calls all match bash). Only the stale-OPTIND > $# entry path diverges. Impact: any script that parses global options then re-invokes its parser per subcommand gets wrong positional args under niu — silent behavior change, the worst compatibility class.

Suggested fix direction: mirror bash's getopts entry clamp (if OPTIND > $# + 1 { OPTIND = $# + 1 }) in the getopts builtin.

2. Multiple negative array subscripts in one expansion spam stderr

a=(aa bb cc); echo "${a[-1]}" "${a[-3]}" "${a[-4]-oob}"
# bash: one "bad array subscript" error (for the genuinely out-of-range [-4]), then "cc aa oob"
# niu : THREE "bad array subscript" errors (for every negative subscript, including valid [-1] [-3]), then "cc aa oob"

Values are correct; the error is emitted spuriously for each negative subscript when several appear in the same command. Isolated single expansions are clean (${a[-1]}/${a[-3]} → no error, ${a[-4]-oob} → exactly one error, both shells). So the multi-expansion path validates negative subscripts against the wrong bounds (or re-runs a check pass per word). Impact: idioms like echo "${arr[-1]} ${arr[-2]}" (last/penultimate element — extremely common) flood stderr in every niu run.

Repro is 100% deterministic. Suggested direction: find the per-word re-validation in the multi-word expansion path; the single-expansion path already has the correct bounds check.

3. history builtin in -c mode dumps the user's interactive history file

bash -c 'history; echo rc=$?'   # prints nothing, rc=0 (non-interactive shells have no history loaded)
niu  -c 'history; echo rc=$?'   # dumps ~42 entries from ~/.niubash_history, rc=0

Non-interactive bash does not load or list history; niu loads the interactive history file even under -c. Impact: history in scripts produces different output; also a mild privacy leak (scripted/batch contexts shouldn't surface the user's interactive history). Related: interactive cross-session history recall appears broken in the opposite direction (file is written at exit, but a new interactive session's Up-arrow/history don't contain the previous session — filed separately on niubash as part of the interactive UX battery).

4. Minor notes (no separate issue, for the record)

  • dirs doesn't tilde-abbreviate $HOME (/etc /tmp /data/data/com.termux/.../home/bench_niu vs bash's /etc /tmp ~/bench_niu).
  • printf '[%d]\n' 42abc: same messages and rc=1, but stdout line renders before the stderr "invalid number" message (bash emits stderr first) — output order differs under 2>&1.
  • enable -f: cleanly rejected with "dynamic loading from echo not supported" (bash tries to load a .so). Honest message; fine as a documented limitation.

Verification matrix (for the fix PR)

The probe battery above + the two focused cases from #610's toolchain: bash -c "<repro>" vs niu -c "<repro>" byte-compared. Cases 1 and 2 have deterministic expected outputs quoted here.

Activity

  1. added
    bug
    P2-medium
    on Oct 15, 2026
  2. caomengxuan666 commented on Oct 15, 2026

    @caomengxuan666
    MemberAuthor

    The Niubash host-history counterpart is now merged as unixwin/niubash#360 (b9cf7f7d). Noninteractive command/script/stdin execution no longer installs the file-backed interactive history provider; explicit history -r/-w remains available. Verified 6 history host-contract tests, 1 interactive-provider regression, the 519-test runtime library suite, and all PR CI checks. Engine getopts/array-diagnostic fixes were already merged in #623. This comment does not claim the separate interactive UX issue unixwin/niubash#355 or the minor observations in this issue are fixed.

  3. caomengxuan666 commented on Oct 16, 2026

    @caomengxuan666
    MemberAuthor

    Verified fixed on master (ea9c18e): (1) getopts stale-OPTIND clamps correctly, (2) multi-negative-subscript emits exactly 1 diagnostic, (3) noninteractive history is clean (niubash#360). Remaining notes: dirs tilde-abbreviation stays divergent (wontfix/documented), printf-merge-order is a buffering artifact (wontfix), enable -f message differs honestly (documented limitation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

P2-mediumbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions