Making your own Linux Shell in C

To know more about what a shell is, click here .

We all use the built in terminal window in Linux distributions like Ubuntu, Fedora, etc. But how do they actually work? In this article, We are going to handle some under the hood features and algorithms what actually work inside a shell. All Linux operating systems have a terminal window to write in commands. But how are they executed properly after they are entered? Also, how are extra features like keeping the history of commands and showing help handled? All of this can be understood by creating your own shell.

The Basics

After a command is entered, the following things are done:

  1. Command is entered and if length is non-null, keep it in history.
  2. Parsing : Parsing is the breaking up of commands into individual words and strings
  3. Checking for special characters like pipes, etc is done
  4. Checking if built-in commands are asked for.
  5. If pipes are present, handling pipes.
  6. Executing system commands and libraries by forking a child and calling execvp .
  7. Printing current directory name and asking for next input.

For keeping history of commands, recovering history using arrow keys and handling autocomplete using the tab key, we will be using the readline library provided by GNU.

Implementation

To install the readline library, open the terminal window and write

sudo apt-get install libreadline-dev

It will ask for your password. Enter it. Press y in the next step.

Here the output has to be taken into the pipe.
Copy file descriptor 1 to stdout.
Close file descriptor 0.
Execute the first command using execvp()
Here the input has to be taken from the pipe.
Copy file descriptor 0 to stdin.
Close file descriptor 1.
Execute the second command using execvp()

To Run the code –

 gcc shell.c -lreadline
./a.out