Skip to content

Conversation

@fangpeina
Copy link
Contributor

@fangpeina fangpeina commented Jan 27, 2026

Summary

This PR implements stderr redirection support in NSH (NuttShell), enabling Bash-like syntax for redirecting standard error output. This enhancement improves NSH compatibility with standard Unix shells and provides better error handling capabilities.

Features Added:

  • Support 2> operator for stderr redirection (overwrite mode)
  • Support 2>> operator for stderr redirection (append mode)
  • Support 2>&1 syntax to redirect stderr to stdout
  • Works with both foreground and background commands

Usage Examples:

nsh> ls noexists 2> err.log           # Redirect stderr to file
nsh> ls noexists 2> err.log &         # Background with stderr redirect
nsh> ls noexists 2>> err.log          # Append stderr to file
nsh> sh < /dev/ttyS0 > /dev/ttyS0 2> /dev/ttyS1 &    # Multiple redirections
nsh> sh < /dev/ttyS0 > /dev/ttyS0 2>&1 &             # Merge stderr to stdout

Impact

  • API Changes: Modified nsh_vtbl_s structure to include stderr file descriptor (internal API only, no user-facing changes)
  • User Experience: Users can now redirect error messages separately from standard output, improving script debugging and error logging
  • Security: No security implications
  • Compatibility: Fully backward compatible - existing NSH commands and scripts continue to work unchanged

Testing

Test Configuration:

  • Platform: Simulation (sim:nsh)
  • Config: sim:nsh

Runtime Test Results:

Test 1: Basic stderr redirection (overwrite mode)

nsh> ll 2> err.log
nsh> cat err.log
nsh: ll: command not found

Test 2: Stderr append mode

nsh> ll 2> err.log
nsh> cat err.log
nsh: ll: command not found
nsh> ls noexists 2>> err.log
nsh> cat err.log
nsh: ll: command not found
nsh: ls: stat failed: 2

Test 3: Redirect stderr to stdout (2>&1)

nsh> ls > log 2>&1
nsh> cat log
/:
 bin/
 data/
 dev/
 err.log
 etc/
 log
 proc/
 tmp/

This commit implements stderr redirection in HSN, support
Bash-like syntax for redirecting standard error output.
Support both foreground and background commands.

example:
- nsh> ls noexists 2> err.log
- nsh> ls noexists 2> err.log &
- nsh> ls noexists 2>> err.log
- nsh> sh < /dev/ttyS0 > /dev/ttyS0 2> /dev/ttyS1 &
- nsh> sh < /dev/ttyS0 > /dev/ttyS0 2>&1 &

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
@fangpeina fangpeina marked this pull request as draft January 27, 2026 04:22
@fangpeina fangpeina closed this Jan 27, 2026
@fangpeina
Copy link
Contributor Author

fangpeina commented Jan 27, 2026

merged

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant