WeCodeAcademy

Step 1: What a shell does

In this project you build a tiny shell in C: the program that reads a line like echo hello > out.txt, understands it and makes the operating system do it. Every time you use a terminal, a shell is running underneath, so building one shows how programs start, how they talk to each other and how a command's exit status works. The examples use real operating-system calls (fork, exec, pipe), run on Linux or macOS, and every output shown is what actually printed.

A shell is a loop: (1) print a prompt, (2) read a line, (3) split it into words, (4) run it, (5) repeat until exit. You will build each part in turn: the loop, a tokenizer, built-in commands, running programs, redirection and pipes. Since a book cannot type at the keyboard, the examples feed the shell a fixed script of commands.

ExampleC
#include <stdio.h>
#include <string.h>

int main(void) {
  // A real shell reads from the keyboard. To keep this example repeatable we feed it a script.
  const char *script[] = { "echo hello", "ls", "exit", "echo never runs" };
  int count = sizeof(script) / sizeof(script[0]);

  for (int i = 0; i < count; i++) {
    printf("tiny> %s\n", script[i]);       // the prompt and the command
    if (strcmp(script[i], "exit") == 0) {
      printf("bye\n");
      break;
    }
    printf("(would run: %s)\n", script[i]);
  }
  return 0;
}
Output
tiny> echo hello
(would run: echo hello)
tiny> ls
(would run: ls)
tiny> exit
bye

Here is the behaviour you are aiming for, using the shell you already know:

Examplebash
Open in editor »
/ $
Quick check

What is the basic structure of a shell?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.