Welcome to Simple Shell, a basic Unix-like shell built from scratch using C++. This shell mimics some common shell behaviors like executing commands, handling built-in commands (cd
, help
, exit
), and more!
- Basic Command Execution: Execute system commands like
ls
,pwd
,echo
, etc. - 🧑💻Built-in Commands:
cd
: Change the current directory.help
: Display helpful information about the shell.exit
: Exit the shell session.
- Process Management: The shell uses
fork()
to create child processes andexecvp()
to replace the child process with the given command. - Command Parsing: Command input is parsed into arguments for execution.
main.cpp
: The main program that runs the shell loop.Buildins_com.hpp
: Contains implementations of built-in commands likecd
,help
, andexit
.
-
Clone the repository:
git clone https://github.com/bilalaniq/Simple-Shell.git cd simple-shell
-
Compile the shell using a C++ compiler (e.g.,
g++
):g++ main.cpp -o simple_shell
-
Run the shell:
./simple_shell
-
Available Commands:
cd <directory>
: Change the current working directory.help
: Display help about available commands.exit
: Exit the shell.
The shell_loop()
function repeatedly prompts the user for input, processes the input into commands and arguments, and executes them using fork()
and execvp()
.
void shell_loop() {
char *line;
char **args;
int status;
do {
std::cout << "> "; // Prompt
line = read_line(); // Read user input
args = get_args(line); // Parse the input into arguments
status = sh_execute(args); // Execute the command
free(line); // Free memory
free(args);
} while (status); // Continue looping
}
The sh_launch()
function creates a child process using fork()
. The child process runs the command via execvp()
, and the parent process waits for the child to finish using waitpid()
.
int sh_launch(char **args) {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("sh");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
// Error forking
perror("sh");
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
Built-in commands like cd
, exit
, and help
are implemented directly in the shell because they need to affect the shell process itself. For example, cd
needs to change the current directory of the shell process, not a child process.
int sh_cd(char **args) {
if (args[1] == NULL) {
std::cerr << "sh: expected argument to \"cd\"\n";
} else {
if (chdir(args[1]) != 0) {
perror("sh");
}
}
return 1;
}
- Currently, only basic functionality for handling external commands is implemented.
- No support for background tasks or piping between commands yet.
This project is licensed under the MIT License - see the LICENSE file for details.
Feel free to fork this project, create issues, or send pull requests with new features or bug fixes! 😊
🚀 Enjoy using Simple Shell! Happy coding! 😎