{"id":22893380,"url":"https://github.com/hoangsonww/c-shell-implementation","last_synced_at":"2025-05-12T13:41:55.986Z","repository":{"id":268023147,"uuid":"903053293","full_name":"hoangsonww/C-Shell-Implementation","owner":"hoangsonww","description":"🔧 A shell implementation in C featuring command parsing, built-in commands, external program execution, and robust memory management for a simplified Unix-like experience. Also includes GoogleTest for unit testing.","archived":false,"fork":false,"pushed_at":"2025-02-05T16:08:15.000Z","size":4399,"stargazers_count":15,"open_issues_count":0,"forks_count":12,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-02-07T01:24:41.720Z","etag":null,"topics":["bash","bash-script","bash-scripting","bashrc","c-language","c-plus-plus","c-programming","c-programming-language","c-sharp","cmake","gcc-complier","python","shell","shell-script","shell-scripting","starlark","valgrind"],"latest_commit_sha":null,"homepage":"https://github.com/hoangsonww/C-Shell-Implementation","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hoangsonww.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-13T20:41:03.000Z","updated_at":"2025-01-23T22:43:37.000Z","dependencies_parsed_at":null,"dependency_job_id":"737e81e4-5802-4592-b2fe-003bf3a1b5aa","html_url":"https://github.com/hoangsonww/C-Shell-Implementation","commit_stats":null,"previous_names":["hoangsonww/c-bash-shell-project"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangsonww%2FC-Shell-Implementation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangsonww%2FC-Shell-Implementation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangsonww%2FC-Shell-Implementation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangsonww%2FC-Shell-Implementation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hoangsonww","download_url":"https://codeload.github.com/hoangsonww/C-Shell-Implementation/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246553005,"owners_count":20795834,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bash","bash-script","bash-scripting","bashrc","c-language","c-plus-plus","c-programming","c-programming-language","c-sharp","cmake","gcc-complier","python","shell","shell-script","shell-scripting","starlark","valgrind"],"created_at":"2024-12-13T23:14:14.922Z","updated_at":"2025-03-31T22:32:47.506Z","avatar_url":"https://github.com/hoangsonww.png","language":"C++","readme":"# Shell Implementation in C\n\nThis project is a simple shell implementation written in C, designed to provide basic shell functionality such as parsing commands, searching for executables in the system's `PATH`, handling built-in commands (`cd`, `exit`), and executing external programs. The shell provides a controlled environment for process management and command execution.\n\n## Table of Contents\n\n1. [Overview](#overview)\n2. [Features](#features)\n3. [File Structure](#file-structure)\n4. [Compilation and Execution](#compilation-and-execution)\n5. [Usage](#usage)\n6. [Code Highlights](#code-highlights)\n7. [Future Improvements](#future-improvements)\n8. [Testing](#testing)\n9. [Acknowledgments](#acknowledgments)\n10. [Author](#author)\n\n## Overview\n\nThe **Shell Implementation in C** provides fundamental features for executing user commands. It includes:\n- Parsing user input into arguments.\n- Identifying commands (both built-in and external).\n- Handling the `PATH` environment variable to locate executables.\n- Executing commands in a child process while the parent process waits.\n- Memory management and error handling to avoid leaks and crashes.\n- Support for built-in commands like `cd` and `exit`.\n- A simple interactive shell interface for user input and output.\n- A Makefile for easy compilation and testing.\n- Unit tests to verify the shell's functionality.\n- Compatibility with GNU/Linux systems.\n\n\n## Features\n\n1. **Command Parsing**: The shell parses user input into tokens (arguments) and constructs a `command` structure.\n2. **Built-in Commands**:\n   - `cd`: Changes the current working directory.\n   - `exit`: Exits the shell.\n3. **External Command Execution**: Supports executing external programs by searching for their full paths using the `PATH` environment variable.\n4. **Memory Management**: Implements dynamic memory allocation using `new` and `delete`, ensuring no memory leaks or dangling pointers.\n5. **Error Handling**: Comprehensive error handling for memory allocation, invalid commands, and execution errors.\n\n## File Structure\n\n- **`shell.h`**: Header file containing definitions, constants, and function prototypes.\n- **`shell.c`**: Main implementation of the shell logic.\n- **`Makefile`**: File for building the project using `make`.\n- **`tests.cpp`**: Unit tests to verify the shell's functionality (optional, if included).\n\n## Compilation and Execution\n\n### Requirements\n- **Operating System**: Must be GNU/Linux system (might be incompatible with Windows or macOS).\n- **C Compiler**: GCC or Clang (with C++ compatibility if using `new`/`delete`).\n- **Make**: Build system utility.\n- **Valgrind** (optional): For memory leak detection.\n\n### Steps to Compile and Run\n1. Clone or download the project to your local machine.\n2. Navigate to the project directory.\n3. Compile the code:\n   ```bash\n   make\n   ```\n4. Run the shell:\n   ```bash\n   ./main\n   ```\n\n### Running with Valgrind\nTo ensure there are no memory leaks:\n```bash\nmake valgrind\n```\n\n## Usage\n\n1. Start the shell:\n   ```bash\n   ./main\n   ```\n2. Enter a command:\n   - Example of a built-in command:\n     ```bash\n     cd /home/user\n     ```\n        or\n        ```bash\n        pwd\n        ```\n   - Example of an external command:\n     ```bash\n     ls -l\n     ```\n3. Exit the shell:\n   ```bash\n   exit\n   ```\n\n## Code Highlights\n\n### 1. Command Parsing\nThe `parse` function takes a user input string, tokenizes it into arguments, and constructs a `command` structure:\n```c\ncommand* parse(char* line) {\n    // Clone input to avoid modifying original\n    char* line_copy = new char[strlen(line) + 1];\n    strcpy(line_copy, line);\n\n    // Tokenize input and count arguments\n    int argc = 0;\n    char* currentToken = strtok(line_copy, \" \\t\\n\");\n    while (currentToken != NULL) {\n        argc++;\n        currentToken = strtok(NULL, \" \\t\\n\");\n    }\n\n    // Create command structure\n    command* cmd = create_command(argc);\n    if (!cmd) return NULL;\n\n    // Populate arguments\n    strcpy(line_copy, line); // Reset line_copy\n    currentToken = strtok(line_copy, \" \\t\\n\");\n    for (int i = 0; i \u003c argc \u0026\u0026 currentToken != NULL; i++) {\n        strncpy(cmd-\u003eargv[i], currentToken, MAX_ARG_LEN - 1);\n        cmd-\u003eargv[i][MAX_ARG_LEN - 1] = '\\0';\n        currentToken = strtok(NULL, \" \\t\\n\");\n    }\n\n    delete[] line_copy;\n    return cmd;\n}\n```\n\n### 2. Built-in Commands\nSupport for built-in commands `cd` and `exit` is implemented in the `do_builtin` function:\n```c\nint do_builtin(command* cmd) {\n    if (strcmp(cmd-\u003eargv[0], \"exit\") == 0) {\n        exit(SUCCESS);\n    }\n    if (cmd-\u003eargc == 1) {\n        return chdir(getenv(\"HOME\")); // cd with no arguments\n    } else if (cmd-\u003eargc == 2) {\n        return chdir(cmd-\u003eargv[1]); // cd with one argument\n    } else {\n        fprintf(stderr, \"cd: Too many arguments\\n\");\n        return ERROR;\n    }\n}\n```\n\n### 3. External Command Execution\nThe shell uses `execv` to execute external commands, following a search in the `PATH` environment variable:\n```c\nbool find_full_path(command* cmd) {\n    char* path_env = getenv(\"PATH\");\n    if (!path_env) return false;\n\n    char* path_copy = new char[strlen(path_env) + 1];\n    strcpy(path_copy, path_env);\n\n    char* currentToken = strtok(path_copy, \":\");\n    while (currentToken != NULL) {\n        char full_path[MAX_LINE_SIZE];\n        snprintf(full_path, sizeof(full_path), \"%s/%s\", currentToken, cmd-\u003eargv[0]);\n\n        struct stat buffer;\n        if (stat(full_path, \u0026buffer) == 0 \u0026\u0026 S_ISREG(buffer.st_mode)) {\n            delete[] cmd-\u003eargv[0];\n            cmd-\u003eargv[0] = new char[strlen(full_path) + 1];\n            strcpy(cmd-\u003eargv[0], full_path);\n\n            delete[] path_copy;\n            return true;\n        }\n        currentToken = strtok(NULL, \":\");\n    }\n\n    delete[] path_copy;\n    return false;\n}\n```\n\n### 4. Memory Management\nMemory is managed using `new` and `delete` throughout the project, ensuring no leaks.\n\n## Future Improvements\n\n1. **Enhanced Built-in Commands**: Add more built-ins like `history` or `export`.\n2. **Background Processing**: Add support for background tasks.\n3. **Advanced Parsing**: Handle pipes (`|`), redirections (`\u003e`, `\u003c`), and quotes.\n4. **Interactive Features**: Improve user experience with command auto-completion and history navigation.\n5. **Error Reporting**: Provide more descriptive error messages for better debugging.\n\n## Testing\n\nUnit tests are provided in the `tests.cpp` file to verify the shell's functionality. The tests cover parsing, built-in commands, external command execution, and memory management. To run the tests, compile the project with the `tests` target:\n```bash\nmake tests\n```\n\nTests are provided using the Google Test framework. You might need to install the Google Test library to run the tests.\n\n## Acknowledgments\n\nThis shell was built as part of a project to understand and implement fundamental system programming concepts in C. It incorporates concepts like dynamic memory allocation, process creation, and system calls, inspired by Unix-based shell functionality.\n\n## Author\n\n**Son Nguyen**  \nGitHub: [hoangsonww](https://github.com/hoangsonww)\n\n---\n\nCreated with ❤️ by [Son Nguyen](https://github.com/hoangsonww) in 2024.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangsonww%2Fc-shell-implementation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhoangsonww%2Fc-shell-implementation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangsonww%2Fc-shell-implementation/lists"}