Skip to content

Latest commit

ย 

History

History
181 lines (124 loc) ยท 7.16 KB

File metadata and controls

181 lines (124 loc) ยท 7.16 KB

๐Ÿš Gosh (Go Shell)

A high-performance interactive Shell written from scratch in Go. A system-level interactive command-line interpreter implemented from scratch, deeply simulating core Bash mechanisms.

Go Version License

English Version | ไธญๆ–‡็‰ˆๆœฌ

**Gosh** is a lightweight, modular Unix-like Shell implementation. It adopts a modern **decoupled architecture design**, completely separating Parsing, Execution, and Builtins.

This project deeply practices the Unix philosophy, implementing efficient multi-stage pipelines and file descriptor redirection through Go concurrency. It is an excellent example for learning operating system process management, IPC communication, and lexical analysis.


โœจ Features

๐Ÿš€ Core Mechanisms

  • Multi-stage Pipelines (|): Supports infinite pipeline operations, automatically managing I/O resources and lifecycles of parent-child processes.
    • Example: ls -l | grep ".go" | wc -l
  • Advanced I/O Redirection:
    • Input Redirection: wc -l < input.txt
    • Output Overwrite: echo "hello" > output.txt
    • Output Append: echo "world" >> output.txt
    • Error Stream Redirection: ls not_exist 2> error.log (Supports 2>> append).

๐Ÿ› ๏ธ Built-ins

  • cd: Change directory (supports intelligent expansion of ~ to the user's home directory).
  • pwd: Display current working directory.
  • echo: Echo text, supports parameter concatenation.
  • history: Powerful history management (supports -w write / -r read).
  • type: Command type detection (distinguishes between Built-in and External).
  • exit: Safely exit and persist history.

๐Ÿ’ป Interaction Experience

  • Line Editing Enhancement: Integrated readline library, supporting cursor movement, deletion, and history backtracking.
  • Smart Completion: Pressing the Tab key automatically completes commands or file paths.
  • State Persistence: Saves history via the HISTFILE environment variable or default strategy, preventing loss upon restart.

๐Ÿง  Implementation Details

This project performs deep module partitioning and logical encapsulation in its underlying implementation:

1. State Management (Session)

  • Global Control: Maintains Shell global variables and standardizes I/O streams (Stdin/Stdout/Stderr), primarily for use by built-in commands in the builtins directory.
  • Convenient Initialization: Provides a NewSession factory method for one-click environment initialization.

2. Parsing Layer (Parse)

  • Pipeline Splitting: The Parse function first physically splits the input string using the | symbol as a delimiter, then encapsulates it into the Pipeline struct for storage.
  • Tokenization (Lexer): parseToken handles finer-grained parsing, processing escape logic for single quotes (') and double quotes ("), further disassembling the string separated by | into concrete Command units. At the low level, a Command is converted into a []string slice.
  • Redirection Parsing: parseSingleCommand performs deep parsing on concrete commands, capable of identifying and processing 5 types of I/O stream redirection (<, >, >>, 2>, 2>>).
    • Key Logic: At this stage, the parser removes I/O redirection identifiers and filenames, purifying the character fragments maintained within the Command into purely "Instruction Name + Arguments", while encapsulating the redirected filenames and modes separately in the Command struct.

3. Execution Engine (Executor)

  • Channel Construction (Execute): The main function of this is to build I/O channels for commands.
    • It iterates through command.args, first handling pipeline redirection logic.
    • It maintains temporary I/O objects internally, constructing file redirections and opening corresponding files based on flags set by the Parse layer.
    • If the current command is not the last in the Pipeline, it builds an os.Pipe channel for connection.
  • Command Scheduling (startSingleCommand):
    • Used to specifically invoke or execute command operations.
    • Concurrency Safety: For built-in commands, an extra Goroutine is constructed for execution to ensure the main function continues running and maintains memory safety, passing errors (err) through channels.
    • Unified Interface: Adopts the WaitFunc interface form to standardize the exit waiting logic of the main function (whether waiting for internal goroutines or external processes).

4. Built-in Commands (Builtins)

  • Function Mapping: Designs internal command operations, mapping command strings to processing functions via a CodFunc map, ensuring concrete function interfaces are not exposed outside the package.
  • Unified Interface: Uses CommandFunc as the unified implementation interface for all built-in command functions, guaranteeing feasibility of direct function invocation via mapping loops.
  • Extensibility: To extend command-line opcodes, simply add corresponding logic in the concrete implementation functions.

5. Entry & Interaction (Main & Readline)

  • Myshell: The entry point of the entire program, initializing Session and Readline.
  • Real-time Interaction: Implements real-time input reading, capturing user input and entering the REPL loop.

๐Ÿ—๏ธ Directory Structure

โ”œโ”€โ”€ cmd/
โ”‚   โ””โ”€โ”€ myshell/
โ”‚       โ”œโ”€โ”€ main.go      # Program entry: Responsible for Session initialization and REPL main loop
โ”‚       โ””โ”€โ”€ readline.go  # Readline configuration and auto-completion logic
โ”œโ”€โ”€ internal/
โ”‚   โ”œโ”€โ”€ builtins/        # Builtin command layer: CodFunc mapping and concrete implementation
โ”‚   โ”œโ”€โ”€ executor/        # Execution engine layer: Execute channel construction and startSingleCommand scheduling
โ”‚   โ”œโ”€โ”€ parser/          # Parsing layer: Pipeline splitting and redirection symbol stripping
โ”‚   โ””โ”€โ”€ session/         # State layer: Global Session management



---

## ๐Ÿ“ฆ Installation & Usage

### Prerequisites

* Go 1.18 or higher
* Linux / macOS environment (Path handling on Windows may differ slightly)

### Quick Run

```bash
# 1. Download dependencies
go mod tidy

# 2. Run Shell
go run cmd/myshell/main.go

Build

# Compile
go build -o gosh cmd/myshell/main.go

# Start
./gosh

๐Ÿ“ Examples

1. Basic Commands and Pipelines

$ ls -l | grep "main.go"

2. File Writing and Reading

# Overwrite
$ echo "Hello Gosh" > hello.txt
# Append
$ echo "Another line" >> hello.txt
# Input Redirection
$ cat < hello.txt

3. Error Log Processing

# Redirect standard error output to file
$ ls /file_not_exist 2> error.log

4. History Operations

# Manually save history to specified file
$ history -w my_history_backup.txt

๐Ÿค Contributing

Pull Requests are welcome. To-Do List (TODO):

  • Support environment variable setting (export).
  • Support logical operators (&&, ||).
  • Support background jobs (&).

๐Ÿ“„ License

MIT License