Skip to content
C project #19Advanced

Mini Shell

A command interpreter with a quote-aware tokeniser, $VARIABLE expansion, history with !N recall, built-ins and delegation to the system shell.

Estimated time
~12 hours to build
Files
8 files · 491 lines
Technologies
C11, <unistd.h> / <direct.h>, system()

Introduction

A shell is the program you talk to in every terminal. Writing one teaches parsing, state management and how programs launch other programs. kenholt-sh implements the core loop of bash in a few hundred readable lines.

Problem statement

Build a read–eval–print loop that tokenises each line (supporting double and single quotes and # comments), expands $NAME and $?, keeps a 20-command history with !N recall, implements built-ins (echo, set, calc, cd, pwd, history, help, exit) and passes any other command to the operating system. It must work interactively and from a script on standard input.

Objectives

  • Write a tokeniser that handles quotes and escapes
  • Implement variable expansion before tokenising
  • Manage a fixed-size circular history
  • Dispatch built-ins and fall back to system()

Features

  • Quotes: "…" (with expansion) and '…' (literal)
  • Variables with validated names and $? for the last status
  • History with !N and an error for unknown events
  • Built-ins plus external commands via system()
  • Portable cd/pwd on Windows and POSIX

Concepts demonstrated

  • Lexical analysis
  • State machines
  • Circular buffers
  • Process exit status
  • Conditional compilation

System architecture

main.c runs the loop: read a line, handle !N, call shell_parse, record history, try run_builtin, otherwise rebuild the command and call system(). parser.c first expands variables into a buffer, then splits it into argv in place, tracking quote state. builtins.c implements each command and updates last_status.

TextArchitecture diagram
line ─> !N recall ─> expand $VARS ─> tokenise (quotes) ─> argv[]
│
built-in? ── yes ─> run_builtin()
│ no
└─> system("cmd args")

Folder structure

TextProject tree
mini-shell/
├── README.md
├── Makefile
├── src/builtins.c
├── src/main.c
├── src/parser.c
├── src/shell.h
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -O2
SRC := $(wildcard src/*.c)
HDR := $(wildcard src/*.h)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CC) $(CFLAGS) -Isrc $(SRC) -o app -lm
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/shell.h
Shell state (history ring, variables, status) and the parser/built-in API.
src/parser.c
Variables, $ expansion and the quote-aware tokeniser.
src/builtins.c
echo, set, calc, cd, pwd, history, help and exit; history recording.
src/main.c
The REPL, !N recall and delegation to the system shell.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
gcc -std=c11 -Wall -Wextra -Isrc src/*.c -o app -lm
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
kenholt-sh 1.0 - type 'help' for commands
ksh> help
Built-in commands:
echo [-n] words... print words
set [NAME=value] list or set shell variables ($NAME expands)
calc A op B integer arithmetic (op: + - x / %)
cd DIR / pwd change / print the working directory
history list recent commands; !N re-runs command N
help / exit [code] this help / leave the shell
Anything else is passed to the system shell.
ksh> echo Hello from kenholt-sh
Hello from kenholt-sh
ksh> set NAME=Asha
ksh> set COURSE="C Programming"
ksh> echo "Welcome, $NAME, to $COURSE"
Welcome, Asha, to C Programming
ksh> echo 'single quotes keep $NAME literal'
single quotes keep $NAME literal
ksh> calc 12 x 7
84
ksh> calc 10 / 0
calc: division by zero
ksh> echo last status was $?
last status was 1
ksh> set 1bad=x
set: invalid name '1bad'
ksh> echo "unterminated
syntax error: unterminated quote or too many arguments
ksh> history
1 help
2 echo Hello from kenholt-sh
3 set NAME=Asha
4 set COURSE="C Programming"
5 echo "Welcome, $NAME, to $COURSE"
6 echo 'single quotes keep $NAME literal'
7 calc 12 x 7
8 calc 10 / 0
9 echo last status was $?
10 set 1bad=x
11 history
ksh> !3
(re-running: set NAME=Asha)
ksh> !99
!99: event not found
ksh> exit
Bye (status 0)
Input
help
echo Hello from kenholt-sh
set NAME=Asha
set COURSE="C Programming"
echo "Welcome, $NAME, to $COURSE"
echo 'single quotes keep $NAME literal'
calc 12 x 7
calc 10 / 0
echo last status was $?
set 1bad=x
echo "unterminated
history
!3
!99
exit

Testing

  • ./app < tests/sample-input.txt must match tests/expected-output.txt (built-ins only, so it is identical on every OS).
  • Interactively run ls (Linux/macOS) or dir (Windows) to see delegation.
  • Try echo "unterminated and check the syntax error.

Common errors

Variables expand inside single quotes

expand tracks single-quote state and copies $ literally while inside them.

External commands with spaces in arguments fail

join_args re-quotes arguments that contain spaces before calling system().

Possible improvements

  • Pipes (a | b) and redirection (> file) using fork/exec/pipe on POSIX
  • Tab completion
  • Aliases

Additional challenges

  1. 1Implement if/then/fi for simple scripts.
  2. 2Run commands with fork/execvp/waitpid instead of system() (POSIX).
  3. 3Add export so variables are passed to child processes.

Built and tested it yourself? Mark it to update your dashboard.