Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Basic Shell

Tags:

For my class I have to create a basic shell similar to bash that will allow the user to call commands like ls, sleep, etc. I am looking for resources on how to do this: tutorials, help text, sample code or even just some general information on how to get started. Does anyone have an links or info to help me out?

like image 211
Bobby S Avatar asked Jan 24 '11 23:01

Bobby S


People also ask

What is an example of a shell?

A shell is a software program used to interpret commands that are input via a command-line interface, enabling users to interact with a computer by giving it instructions. Some examples of shells are MS-DOS Shell (command.com), csh, ksh, PowerShell, sh, and tcsh.

What is shell Basic?

A shell is a special user program that provides an interface to the user to use operating system services. Shell accepts human-readable commands from the user and converts them into something which the kernel can understand.


1 Answers

It really depends on how simple your shell has to be. If you don't need job control (i.e. backgrounding) or pipes then it is very simple. Here is an example:

#include <stdio.h> #include <stdlib.h>  #define MAX_LENGTH 1024  int main(int argc, char *argv[]) {   char line[MAX_LENGTH];    while (1) {     printf("$ ");     if (!fgets(line, MAX_LENGTH, stdin)) break;     system(line);   }    return 0; } 

You can exit from the above example with CTRL-D. To add built-in commands like exit or cd you would have to tokenize the line using strtok() and look at the first token. Here is a more complicated example with those commands added:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h>  #ifdef _WIN32 #include <windows.h> #define chdir _chdir  #else #include <unistd.h> #endif  #define MAX_LENGTH 1024 #define DELIMS " \t\r\n"  int main(int argc, char *argv[]) {   char *cmd;   char line[MAX_LENGTH];    while (1) {     printf("$ ");     if (!fgets(line, MAX_LENGTH, stdin)) break;      // Parse and execute command     if ((cmd = strtok(line, DELIMS))) {       // Clear errors       errno = 0;        if (strcmp(cmd, "cd") == 0) {         char *arg = strtok(0, DELIMS);          if (!arg) fprintf(stderr, "cd missing argument.\n");         else chdir(arg);        } else if (strcmp(cmd, "exit") == 0) {         break;        } else system(line);        if (errno) perror("Command failed");     }   }    return 0; } 

You could extend this by adding more build-in commands or by supporting things like cd with out arguments to change to your home directory. You could also improve the command prompt by adding information such as the current directory.

As a side note, an easy way to add a command history and line editing features is to use the GNU readline library.

like image 187
jcoffland Avatar answered Oct 19 '22 15:10

jcoffland