Postly.
HomeBlogAsk
Postly.Stories worth reading.
BlogAskWriteRSS
All posts
#java#shell#linux#from-scratch

Implementing a Unix shell in Java using ProcessBuilder and JLine

Quoting, PATH lookup, redirection, pipelines, background jobs and tab completion in a shell written in Java.

AGAryan GargNov 24, 20264 min read2 views
7
Dark terminal-style cover with shell commands, a pipeline and a background job next to the title A Unix shell in Java
7

TL;DR · AI summary

Learn how to build a functional POSIX-style shell in Java using ProcessBuilder and JLine. This guide covers essential shell mechanics including command parsing, pipeline execution, redirection, and managing background jobs.

A shell feels like part of the operating system, but it's an ordinary program: read a line, figure out what it means, start some processes, wait for them. I implemented a POSIX-style shell in Java to find out how much is hiding behind the $ prompt.

It has builtins (echo, type, pwd, cd, exit, history, jobs, declare, complete), runs any program on your PATH, and supports quoting, output redirection, pipelines, background jobs, variables, persistent history, syntax highlighting and tab completion.

The loop

At its core a shell is a REPL:

while (true) {
  jobManager.reapCompletedJobs();
  String input = reader.readLine("$ ").trim();
  if (input.equalsIgnoreCase("exit")) break;

  if (input.contains("|")) handlePipeline(input);
  else executeSingleCommand(ParsedCommand.parse(input));
}

The reader is JLine, which gives me line editing, arrow-key history and hooks for highlighting and completion. More on those later.

Tokenizing: quotes are the hard part

Splitting echo hello world on spaces is easy. Splitting this correctly is not:

echo "it's a \"test\"" 'single $HOME' back\ slash

The rules, roughly:

  • Inside single quotes, everything is literal. No escapes at all.

  • Inside double quotes, a backslash only escapes \, ", $, a backtick or a newline. Before anything else, the backslash is kept.

  • Outside quotes, a backslash escapes the next character, including a space.

  • Unquoted spaces separate arguments, and adjacent quoted parts join into one word.

I implemented this as a single pass with three flags:

for (char ch : content.toCharArray()) {
  if (isBackslash) {
    if (inDouble && !"\\\"$`\n".contains(String.valueOf(ch))) part.append('\\');
    part.append(ch);
    isBackslash = false;
  }
  else if (ch == '\\' && !inSingle) isBackslash = true;
  else if (ch == '"' && !inSingle) inDouble = !inDouble;
  else if (ch == '\'' && !inDouble) inSingle = !inSingle;
  else if (ch == ' ' && !inDouble && !inSingle) {
    if (!part.isEmpty()) { parts.add(part.toString()); part.setLength(0); }
  }
  else part.append(ch);
}

Writing tests for the weird cases first ('a'"b"c should be one word, abc) saved me a lot of time.

Finding programs

When the command isn't a builtin, the shell searches each directory in PATH for an executable file with that name. The type builtin exposes the same lookup:

$ type echo
echo is a shell builtin
$ type git
git is /usr/bin/git

Redirection

After tokenizing, the parser looks for redirection operators and strips them from the argument list:

  • > and 1> write stdout to a file, >> and 1>> append.

  • 2> and 2>> do the same for stderr.

For external programs, Java's ProcessBuilder handles this directly:

builder.redirectOutput(append
  ? ProcessBuilder.Redirect.appendTo(path.toFile())
  : ProcessBuilder.Redirect.to(path.toFile()));

Builtins write to a PrintStream instead, which is either System.out or a stream opened on the target file.

Pipelines

cat log.txt | grep ERROR | wc -l connects the stdout of each process to the stdin of the next. Java has a method that does exactly this:

List<Process> processes = ProcessBuilder.startPipeline(builders);

Only the first command may redirect stdin and only the last may redirect stdout. Then the shell waits for every process and uses the last one's exit code.

The tricky case is builtins inside a pipeline, like echo hi | wc -c. A builtin is a Java method, not a process, so there's no stdout to connect. My solution was to start the shell itself as a child process in single-command mode:

if (BUILTIN_COMMANDS.contains(command.command())) {
  args.add("./your_program.sh");
  args.add("-c");
  args.add(command.command() + " " + String.join(" ", command.args()));
}

That's what real shells do too: each part of a pipeline runs in a subshell.

Background jobs

Ending a command with & starts it without waiting. A JobManager keeps running jobs in a TreeMap keyed by job number, and before showing each prompt the shell reaps finished jobs and reports them, the same way bash prints [1]+ Done. The jobs builtin lists what's still running.

Variables

declare NAME=value stores a variable, and arguments are expanded before a command runs. Both $NAME and ${NAME} are supported with one regex:

Pattern.compile("\\$\\{([^}]+)}|\\$([A-Za-z_][0-9A-Za-z_]*)");

The interactive parts: JLine

This is where the shell started to feel real.

  • Syntax highlighting. A custom Highlighter colors builtin names as you type.

  • History. Arrow keys recall previous commands, duplicates are skipped, and history -r, -w and -a read, write and append history files. History is saved on exit with a shutdown hook.

  • Tab completion. A custom widget completes builtins and executables. With several matches it completes the longest common prefix. If there's nothing more to add, the first Tab rings the bell and the second Tab lists every option. The complete builtin can register custom completers for specific commands.

What I'd do differently

  • Parse pipes in the tokenizer. Splitting the input on | before tokenizing breaks echo "a|b". Pipes should be operator tokens produced by the same quote-aware pass.

  • Build a small AST. Commands, pipelines, redirections and & form a grammar. Representing it explicitly would make adding &&, || and ; straightforward.

  • Split the single file. The shell grew to over a thousand lines in one Main.java. Tokenizer, parser, executor, job control and the JLine glue each deserve their own class.

  • Merge streams. 2>&1 needs redirectErrorStream(true) for processes and a shared stream for builtins.

The best part of this project was seeing that the "magic" of a terminal is a pile of small, understandable rules. Quoting alone taught me more about parsing than any textbook exercise.

On this page

  • The loop
  • Tokenizing: quotes are the hard part
  • Finding programs
  • Redirection
  • Pipelines
  • Background jobs
  • Variables
  • The interactive parts: JLine
  • What I'd do differently

Discussion(0)

    Loading comments…