Interpreting user request
The user asked for a POSIX-compliant shell with scripting capabilities, which feels a bit ambiguous to me. They could mean code for a shell like /bin/sh or guidance on its design. I wonder if they want a shell script that meets POSIX standards or a full shell program, maybe in C, with scripting features. Given the complexities of fully implementing POSIX, it might be better to focus on a simpler, educational example instead. I'll need to navigate OpenAI's policies too.Considering shell implementation
The task is complex, but I think I can create a minimal interactive shell that implements a subset of POSIX features and explain what's lacking for full compliance. While they specified "POSIX-compliant," I should clarify or make certain assumptions. I can propose a shell implementation in C that uses POSIX APIs for reading lines, parsing, supporting pipelines, redirection, and basic scripting with built-in commands like cd, exit, and control constructs. instead of a full implementation, I’ll focus on providing an architecture and skeleton code.Planning shell implementation
I'm planning to explain the constraints of creating a fully POSIX-compliant shell since that's quite extensive. Instead, I’m thinking of offering a minimal yet standards-conscious shell along with design guidance for further extensions. Choosing C seems natural, and I’ll utilize POSIX APIs like fork, execve, and pipe.
I’ll summarize requirements for POSIX shells, including aspects like lexical conventions and built-ins. Then, I'll sketch out a high-level architecture that features a tokenizer, parser (maybe covering simple commands and control structures), and an executor, plus options for both interactive and script modes.Drafting shell code requirements
I need to provide C code for a basic interactive and script shell with several functionalities. Firstly, it should read commands from standard input or a script file. I’ll include tokenization that handles quotes, escapes, and simple variable expansions, limited to environment variables. The parsing needs to cover a basic grammar of simple command sequences and possibly pipelines, while execution will need to support built-ins like cd, exit, and variable management.
I should clarify what’s missing for full POSIX compliance while pointing to the POSIX standard. Since they want a shell that's "create"-focused, I can offer code ready to compile, along with compile instructions using gcc. I’ll aim to keep the code manageable, avoiding excessive length while being concise, as they didn’t specify minimal or thorough.Structuring shell code approach
I’m thinking I should start with an introductory textual explanation before diving into the code with helpful comments. I want to ensure my implementation is original and doesn’t replicate existing shells like dash or bash. The grammar I’m designing will be minimal, with a command line structure defined as a sequence of pipelines, separated by semicolons or new lines.
Each pipeline can involve commands linked by pipes, and commands will handle assignments, redirections, and words. I’ll also include basic redirection handling but skip various complexities like logical operators, wildcard expansions, and braces for simplicity.Defining tokenization and scripting
For the tokenization process, I’ll handle whitespace separation, but not within quotes. Basic backslash escapes will be recognized outside of quotes, and I'll support variable expansion for environment variables using $VAR. I won’t fully implement quoting semantics, but I need to clarify that my implementation won't be fully POSIX-compliant.
I'll include a shebang in the script to enable script mode, allowing execution from script files. My proposed code structure involves defining token types and using simple functions for parsing.
Execution will require handling both built-in commands and pipelines effectively. For scripting capabilities, I can interpret this as executing commands from a text file, along with supporting simple variables and comments. I’ll keep the implementation minimal, noting what features are missing for completeness.Designing the shell features
I need to implement environment variable expansion by performing a second pass after tokenization. I’ll design the expand_word function to look for $VAR or ${VAR} and substitute using getenv, parsing the string character by character. I won’t include positional parameters like $? or $#.
Next, I’ll define the Command structure to handle command arguments and redirection, with the ability to dynamically expand command capacity. The parsing will be done in the parse_command function.
I plan to manage pipelines through a Pipeline structure, allowing me to store commands as an array rather than building a full AST. The main loop will execute commands sequentially, and I’ll implement built-ins like cd and exit, running them directly in the parent process when they modify the shell environment.
For scripting, I’ll allow users to specify a script file as an argument. I’ll handle reading lines and maintaining interactivity through prompts. Although some advanced features will be skipped, I will provide a straightforward implementation for this minimal shell environment.Implementing shell features and tokenization
I need to handle edge cases for pipelines with redirections, like cat < in | sort > out. For the execution of pipelines, I'll set up file descriptors and use fork() and execvp() for command execution.
I'll ensure to manage input/output redirection, clean up resources, and handle errors appropriately with perror(). It's essential to differentiate between interactive and script modes, which means implementing prompts.
For tokenization, I’ll create an efficient system that parses lines character-by-character, handling quotes and special characters while maintaining a buffer for words. I’ll also develop an expansion stage for tokens, ensuring environment variables are replaced correctly.
I want to ensure everything stays POSIX-compliant while still having robust error handling and memory management practices in place.Expanding words and parsing commands
I’m implementing a function to expand environment variables in strings. It will handle $VAR and ${VAR} formats. I'm keeping track of buffer limits to avoid overflow.
Next, I'll code the token parsing functions, ensuring I manage memory properly by initializing and resizing structures where necessary. For command parsing, I need to handle redirections while checking the syntax for errors, like ensuring filenames follow redirection tokens.
In the process, I'll set up the pipeline parsing to manage multiple commands effectively, with careful memory management during execution and cleanup phases. It’s essential to keep things organized!Implementing pipeline execution
I'm working on the execute_pipeline function that processes command pipelines. If there are no commands, it should return 0. If there’s just one command and it’s a built-in, I will handle it using exec_builtin.
When there are multiple commands, I need to use pipes for connecting their input and output. Each child process will set up its input and output based on redirections and pipes. I’ll then wait for all child processes to finish and gather their exit statuses.
Next, I need to implement built-in commands like cd, exit, and echo. I’ll also ensure resource management, especially for free tokens at the end! It's a lot to track, but I’ll keep it organized!Finalizing main functionality
I'm working on the main function, which handles input, either from the terminal or a file. If arguments are passed as -c, I'll need to implement that part later.
Right now, I’ll read lines and tokenize them. I've noticed that the shell processes one line at a time and can't yet handle multi-line commands. I want to ensure that tokenization works correctly, including expansions for variables while respecting quoting rules.
I plan to include error handling for long commands and manage resources efficiently, especially for freeing tokens!Structuring a minimal POSIX-style shell
I'm considering a minimal POSIX-style shell implementation that handles basic scripting. While it won't be fully compliant with POSIX standards, it will utilize POSIX calls. I need to be clear about this limitation in my response to the user.
I'm planning to outline supported features like external commands, built-in commands (cd/exit/echo/pwd), pipes, redirection, and variable expansion. I’ll present the code as one block for easy copying, along with compilation and running instructions. I also want to ensure we handle the necessary definitions and functions in the right order in the code.
The focus will be on clarity and usability for the user while keeping explanations concise.Implementing command pipeline functions
I’m developing functions for a command pipeline, starting with init_pipeline to initialize it. I need to ensure I can dynamically add commands with add_command. If I exceed the initial capacity, I’ll reallocate memory for more commands. In parse_pipeline, I'll initialize the pipeline and handle potential errors gracefully, making sure to clean up resources if parsing fails.
I’m incorporating handling for tokens and comments based on the position relative to whitespace. All functions need to work together seamlessly, especially when processing commands and expansions. Also, I've considered how built-in functions will operate, like pwd and cd, ensuring they are called appropriately without causing issues for the parent process.Finalizing the code structure
I need to ensure free_tokens sets ntok to zero. I'll add compile instructions and craft a final answer that includes only the code, while mentioning necessary disclaimers. It's important to double-check that no function names conflict with existing macros, particularly with the types "Command" and "Pipeline."
After that, I’ll organize the code properly, starting with the necessary preprocessor directives, includes, and macros, followed by helper functions, all in one structured code block. Finally, I’ll ensure I'm using constant arrays and not variable-length arrays. Below is a small, self‑contained POSIX‑style shell implemented in C.
It:
- Uses only POSIX APIs (
fork, execvp, pipe, dup2, etc.).
- Supports:
- Running external commands
- Builtins:
cd, pwd, echo, exit
- Pipelines:
cmd1 | cmd2 | cmd3
- Redirection:
< file, > file, >> file
- Simple
$VAR / ${VAR} environment expansion
- Comments starting with
# (outside of words)
- Interactive mode (prompt) and script mode (
./minish script.sh)
It is not fully POSIX shell‑language compliant (control structures, full quoting/expansion rules, etc. are missing), but it’s a usable, minimal shell with scripting.
Source code (minish.c)
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <ctype.h>
#include <fcntl.h>
/* ---------- Configuration ---------- */
#define MAX_LINE 4096
#define MAX_TOKENS 512
#define MAX_EXPANDED 8192
/* ---------- Utility helpers ---------- */
static void *xmalloc(size_t n) {
void *p = malloc(n);
if (!p) {
perror("malloc");
exit(1);
}
return p;
}
static void *xrealloc(void *p, size_t n) {
void *q = realloc(p, n);
if (!q) {
perror("realloc");
exit(1);
}
return q;
}
static char *xstrdup(const char *s) {
size_t len = strlen(s) + 1;
char *p = xmalloc(len);
memcpy(p, s, len);
return p;
}
/* ---------- Tokenizer ---------- */
enum TokenType {
TT_WORD,
TT_PIPE, /* | */
TT_SEMI, /* ; */
TT_LT, /* < */
TT_GT, /* > */
TT_DGT, /* >> */
TT_EOL, /* end of line */
TT_EOF
};
struct Token {
enum TokenType type;
char *text; /* only for TT_WORD */
};
struct TokenStream {
struct Token tokens[MAX_TOKENS];
int ntok;
int pos;
};
static void add_token(struct TokenStream *ts, enum TokenType type, const char *text) {
if (ts->ntok >= MAX_TOKENS) {
fprintf(stderr, "Too many tokens in one line\n");
return;
}
ts->tokens[ts->ntok].type = type;
ts->tokens[ts->ntok].text = text ? xstrdup(text) : NULL;
ts->ntok++;
}
static void tokenize_line(const char *line, struct TokenStream *ts) {
int in_squote = 0;
int in_dquote = 0;
int escape = 0;
char buf[MAX_LINE];
int blen = 0;
ts->ntok = 0;
ts->pos = 0;
#define FLUSH_WORD() \
do { \
if (blen > 0) { \
buf[blen] = '\0'; \
add_token(ts, TT_WORD, buf); \
blen = 0; \
} \
} while (0)
for (int i = 0; ; i++) {
char c = line[i];
if (c == '\0') {
FLUSH_WORD();
break;
}
if (escape) {
buf[blen++] = c;
escape = 0;
continue;
}
if (!in_squote && c == '\\') {
escape = 1;
continue;
}
if (in_squote) {
if (c == '\'') {
in_squote = 0;
} else {
buf[blen++] = c;
}
continue;
}
if (in_dquote) {
if (c == '"') {
in_dquote = 0;
} else {
buf[blen++] = c;
}
continue;
}
/* Not in quotes here */
if (c == '\'') {
in_squote = 1;
continue;
}
if (c == '"') {
in_dquote = 1;
continue;
}
if (c == ' ' || c == '\t') {
FLUSH_WORD();
continue;
}
if (c == '\n') {
FLUSH_WORD();
add_token(ts, TT_EOL, NULL);
break;
}
if (c == '#') {
/* If at start of a new word, treat as comment; else part of word */
if (blen == 0) {
/* Comment: ignore rest of line */
break;
} else {
buf[blen++] = c;
continue;
}
}
if (c == '|') {
FLUSH_WORD();
add_token(ts, TT_PIPE, NULL);
continue;
}
if (c == ';') {
FLUSH_WORD();
add_token(ts, TT_SEMI, NULL);
continue;
}
if (c == '<') {
FLUSH_WORD();
add_token(ts, TT_LT, NULL);
continue;
}
if (c == '>') {
FLUSH_WORD();
if (line[i + 1] == '>') {
i++;
add_token(ts, TT_DGT, NULL);
} else {
add_token(ts, TT_GT, NULL);
}
continue;
}
/* Regular character */
buf[blen++] = c;
}
FLUSH_WORD();
/* Ensure line terminator token */
if (ts->ntok == 0 || ts->tokens[ts->ntok - 1].type != TT_EOL) {
add_token(ts, TT_EOL, NULL);
}
#undef FLUSH_WORD
}
/* ---------- Expansion ---------- */
static char *expand_word(const char *s) {
char buf[MAX_EXPANDED];
int j = 0;
for (int i = 0; s[i] != '\0' && j < MAX_EXPANDED - 1; ) {
if (s[i] == '$') {
if (s[i + 1] == '{') {
/* ${VAR} */
int k = i + 2;
while (s[k] && s[k] != '}')
k++;
if (s[k] == '}') {
int len = k - (i + 2);
if (len > 0) {
char name[256];
if (len >= (int)sizeof(name))
len = (int)sizeof(name) - 1;
memcpy(name, &s[i + 2], len);
name[len] = '\0';
const char *val = getenv(name);
if (val) {
for (int m = 0; val[m] && j < MAX_EXPANDED - 1; m++)
buf[j++] = val[m];
}
}
i = k + 1;
continue;
} else {
/* No closing }, treat $ literally */
buf[j++] = s[i++];
continue;
}
} else if (s[i + 1] == '_' || isalpha((unsigned char)s[i + 1])) {
/* $VAR */
int k = i + 1;
while (isalnum((unsigned char)s[k]) || s[k] == '_')
k++;
int len = k - (i + 1);
char name[256];
if (len >= (int)sizeof(name))
len = (int)sizeof(name) - 1;
memcpy(name, &s[i + 1], len);
name[len] = '\0';
const char *val = getenv(name);
if (val) {
for (int m = 0; val[m] && j < MAX_EXPANDED - 1; m++)
buf[j++] = val[m];
}
i = k;
continue;
} else {
/* Just a '$' character */
buf[j++] = s[i++];
continue;
}
} else {
buf[j++] = s[i++];
}
}
buf[j] = '\0';
return xstrdup(buf);
}
static void expand_tokens(struct TokenStream *ts) {
for (int i = 0; i < ts->ntok; i++) {
if (ts->tokens[i].type == TT_WORD && ts->tokens[i].text) {
char *neww = expand_word(ts->tokens[i].text);
free(ts->tokens[i].text);
ts->tokens[i].text = neww;
}
}
}
/* ---------- Parser data structures ---------- */
struct Command {
char **argv;
int argc;
int cap;
char *infile;
char *outfile;
int append; /* 0: >, 1: >> */
};
struct Pipeline {
struct Command *cmds;
int ncmds;
int cap;
};
/* ---------- TokenStream helpers ---------- */
static enum TokenType peek_type(struct TokenStream *ts) {
if (ts->pos >= ts->ntok)
return TT_EOF;
return ts->tokens[ts->pos].type;
}
static struct Token *get_token(struct TokenStream *ts) {
if (ts->pos >= ts->ntok)
return NULL;
return &ts->tokens[ts->pos++];
}
/* ---------- Command / pipeline helpers ---------- */
static void init_command(struct Command *cmd) {
cmd->argc = 0;
cmd->cap = 4;
cmd->argv = xmalloc(cmd->cap * sizeof(char *));
cmd->argv[0] = NULL;
cmd->infile = NULL;
cmd->outfile = NULL;
cmd->append = 0;
}
static void add_arg(struct Command *cmd, const char *word) {
if (cmd->argc + 1 >= cmd->cap) {
cmd->cap *= 2;
cmd->argv = xrealloc(cmd->argv, cmd->cap * sizeof(char *));
}
cmd->argv[cmd->argc++] = xstrdup(word);
cmd->argv[cmd->argc] = NULL;
}
static void free_command(struct Command *cmd) {
for (int i = 0; i < cmd->argc; i++)
free(cmd->argv[i]);
free(cmd->argv);
free(cmd->infile);
free(cmd->outfile);
}
static void init_pipeline(struct Pipeline *pl) {
pl->ncmds = 0;
pl->cap = 2;
pl->cmds = xmalloc(pl->cap * sizeof(struct Command));
}
static void add_command_to_pipeline(struct Pipeline *pl, struct Command *cmd) {
if (pl->ncmds >= pl->cap) {
pl->cap *= 2;
pl->cmds = xrealloc(pl->cmds, pl->cap * sizeof(struct Command));
}
pl->cmds[pl->ncmds++] = *cmd; /* shallow copy is fine */
}
static void free_pipeline(struct Pipeline *pl) {
for (int i = 0; i < pl->ncmds; i++)
free_command(&pl->cmds[i]);
free(pl->cmds);
}
/* ---------- Parser ---------- */
static int parse_command(struct TokenStream *ts, struct Command *cmd) {
init_command(cmd);
int saw_word = 0;
for (;;) {
enum TokenType tt = peek_type(ts);
if (tt == TT_WORD) {
struct Token *t = get_token(ts);
add_arg(cmd, t->text);
saw_word = 1;
} else if (tt == TT_LT || tt == TT_GT || tt == TT_DGT) {
struct Token *t = get_token(ts); /* consume redirection symbol */
enum TokenType rt = t->type;
if (peek_type(ts) != TT_WORD) {
fprintf(stderr, "syntax error: expected filename after redirection\n");
return -1;
}
struct Token *fname = get_token(ts);
if (rt == TT_LT) {
free(cmd->infile);
cmd->infile = xstrdup(fname->text);
} else {
free(cmd->outfile);
cmd->outfile = xstrdup(fname->text);
cmd->append = (rt == TT_DGT);
}
} else {
break;
}
}
if (!saw_word) {
/* No actual command; e.g., blank before EOL/SEMI/PIPE */
free_command(cmd);
return 0;
}
return 1;
}
static int parse_pipeline(struct TokenStream *ts, struct Pipeline *pl) {
init_pipeline(pl);
struct Command cmd;
int r = parse_command(ts, &cmd);
if (r <= 0) {
free(pl->cmds);
pl->cmds = NULL;
pl->ncmds = pl->cap = 0;
return r;
}
add_command_to_pipeline(pl, &cmd);
while (peek_type(ts) == TT_PIPE) {
get_token(ts); /* consume '|' */
struct Command cmd2;
int r2 = parse_command(ts, &cmd2);
if (r2 <= 0) {
fprintf(stderr, "syntax error: expected command after pipe\n");
free_pipeline(pl);
return -1;
}
add_command_to_pipeline(pl, &cmd2);
}
return 1;
}
/* ---------- Builtins ---------- */
static int is_builtin(const char *name) {
if (!name)
return 0;
return strcmp(name, "cd") == 0 ||
strcmp(name, "pwd") == 0 ||
strcmp(name, "echo") == 0 ||
strcmp(name, "exit") == 0;
}
static int builtin_cd(struct Command *cmd) {
const char *path;
if (cmd->argc > 1) {
path = cmd->argv[1];
} else {
path = getenv("HOME");
if (!path) {
fprintf(stderr, "cd: HOME not set\n");
return 1;
}
}
if (chdir(path) != 0) {
perror("cd");
return 1;
}
return 0;
}
static int builtin_pwd(struct Command *cmd) {
(void)cmd;
char *cwd = getcwd(NULL, 0);
if (!cwd) {
perror("pwd");
return 1;
}
printf("%s\n", cwd);
free(cwd);
return 0;
}
static int builtin_echo(struct Command *cmd) {
for (int i = 1; i < cmd->argc; i++) {
fputs(cmd->argv[i], stdout);
if (i + 1 < cmd->argc)
fputc(' ', stdout);
}
fputc('\n', stdout);
return 0;
}
static int builtin_exit(struct Command *cmd) {
int status = 0;
if (cmd->argc > 1) {
status = (int)strtol(cmd->argv[1], NULL, 10);
}
exit(status);
}
static int run_builtin(struct Command *cmd) {
const char *name = cmd->argv[0];
if (strcmp(name, "cd") == 0) return builtin_cd(cmd);
if (strcmp(name, "pwd") == 0) return builtin_pwd(cmd);
if (strcmp(name, "echo") == 0) return builtin_echo(cmd);
if (strcmp(name, "exit") == 0) return builtin_exit(cmd);
return 1; /* should not reach */
}
/* Run builtin in the current process, applying simple redirections */
static int exec_builtin_in_parent(struct Command *cmd) {
int saved_stdin = -1, saved_stdout = -1;
int in_fd = -1, out_fd = -1;
if (cmd->infile) {
in_fd = open(cmd->infile, O_RDONLY);
if (in_fd < 0) {
perror(cmd->infile);
return 1;
}
}
if (cmd->outfile) {
int flags = O_WRONLY | O_CREAT;
flags |= cmd->append ? O_APPEND : O_TRUNC;
out_fd = open(cmd->outfile, flags, 0666);
if (out_fd < 0) {
perror(cmd->outfile);
if (in_fd >= 0) close(in_fd);
return 1;
}
}
if (in_fd >= 0) {
saved_stdin = dup(STDIN_FILENO);
if (saved_stdin < 0 || dup2(in_fd, STDIN_FILENO) < 0) {
perror("dup/dup2");
if (in_fd >= 0) close(in_fd);
if (out_fd >= 0) close(out_fd);
return 1;
}
close(in_fd);
}
if (out_fd >= 0) {
saved_stdout = dup(STDOUT_FILENO);
if (saved_stdout < 0 || dup2(out_fd, STDOUT_FILENO) < 0) {
perror("dup/dup2");
if (out_fd >= 0) close(out_fd);
if (saved_stdin >= 0) {
dup2(saved_stdin, STDIN_FILENO);
close(saved_stdin);
}
return 1;
}
close(out_fd);
}
int status = run_builtin(cmd);
if (saved_stdin >= 0) {
dup2(saved_stdin, STDIN_FILENO);
close(saved_stdin);
}
if (saved_stdout >= 0) {
dup2(saved_stdout, STDOUT_FILENO);
close(saved_stdout);
}
return status;
}
/* ---------- Executor ---------- */
static int execute_pipeline(struct Pipeline *pl) {
if (pl->ncmds == 0)
return 0;
/* Single built-in: run in parent so it can affect shell state */
if (pl->ncmds == 1 && is_builtin(pl->cmds[0].argv[0])) {
return exec_builtin_in_parent(&pl->cmds[0]);
}
int n = pl->ncmds;
pid_t *pids = xmalloc(sizeof(pid_t) * n);
int in_fd = STDIN_FILENO;
for (int i = 0; i < n; i++) {
int fd[2] = { -1, -1 };
if (i < n - 1) {
if (pipe(fd) < 0) {
perror("pipe");
free(pids);
return 1;
}
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
if (fd[0] != -1) close(fd[0]);
if (fd[1] != -1) close(fd[1]);
free(pids);
return 1;
}
if (pid == 0) {
/* Child */
struct Command *cmd = &pl->cmds[i];
/* Input redirection or pipe-in */
if (cmd->infile) {
int f = open(cmd->infile, O_RDONLY);
if (f < 0) {
perror(cmd->infile);
_exit(1);
}
if (dup2(f, STDIN_FILENO) < 0) {
perror("dup2");
_exit(1);
}
close(f);
} else if (in_fd != STDIN_FILENO) {
if (dup2(in_fd, STDIN_FILENO) < 0) {
perror("dup2");
_exit(1);
}
}
/* Output redirection or pipe-out */
if (cmd->outfile) {
int flags = O_WRONLY | O_CREAT;
flags |= cmd->append ? O_APPEND : O_TRUNC;
int f = open(cmd->outfile, flags, 0666);
if (f < 0) {
perror(cmd->outfile);
_exit(1);
}
if (dup2(f, STDOUT_FILENO) < 0) {
perror("dup2");
_exit(1);
}
close(f);
} else if (i < n - 1) {
if (dup2(fd[1], STDOUT_FILENO) < 0) {
perror("dup2");
_exit(1);
}
}
/* Close unused fds */
if (fd[0] != -1) close(fd[0]);
if (fd[1] != -1) close(fd[1]);
if (in_fd != STDIN_FILENO)
close(in_fd);
if (is_builtin(cmd->argv[0])) {
int st = run_builtin(cmd);
_exit(st);
} else {
execvp(cmd->argv[0], cmd->argv);
perror(cmd->argv[0]);
_exit(127);
}
} else {
/* Parent */
pids[i] = pid;
if (in_fd != STDIN_FILENO)
close(in_fd);
if (i < n - 1) {
close(fd[1]);
in_fd = fd[0];
}
}
}
if (in_fd != STDIN_FILENO)
close(in_fd);
int last_status = 0;
for (int i = 0; i < n; i++) {
int status;
if (waitpid(pids[i], &status, 0) < 0) {
perror("waitpid");
} else {
if (WIFEXITED(status))
last_status = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
last_status = 128 + WTERMSIG(status);
}
}
free(pids);
return last_status;
}
/* ---------- Token cleanup ---------- */
static void free_tokens(struct TokenStream *ts) {
for (int i = 0; i < ts->ntok; i++) {
free(ts->tokens[i].text);
}
ts->ntok = 0;
ts->pos = 0;
}
/* ---------- Main loop ---------- */
int main(int argc, char **argv) {
FILE *input = stdin;
int interactive = isatty(STDIN_FILENO);
if (argc > 1) {
input = fopen(argv[1], "r");
if (!input) {
perror(argv[1]);
return 1;
}
interactive = 0;
}
char line[MAX_LINE];
for (;;) {
if (interactive) {
fputs("$ ", stdout);
fflush(stdout);
}
if (!fgets(line, sizeof(line), input)) {
break; /* EOF */
}
struct TokenStream ts;
tokenize_line(line, &ts);
if (ts.ntok == 0) {
continue;
}
expand_tokens(&ts);
while (ts.pos < ts.ntok) {
enum TokenType tt = peek_type(&ts);
if (tt == TT_EOL || tt == TT_EOF)
break;
struct Pipeline pl;
int r = parse_pipeline(&ts, &pl);
if (r <= 0) {
if (r < 0)
fprintf(stderr, "parse error\n");
break;
}
execute_pipeline(&pl);
free_pipeline(&pl);
tt = peek_type(&ts);
if (tt == TT_SEMI) {
get_token(&ts); /* consume ';' and continue */
continue;
}
if (tt == TT_EOL || tt == TT_EOF)
break;
}
free_tokens(&ts);
}
if (input != stdin)
fclose(input);
return 0;
}
Building and using
Compile (on a POSIX system with a C compiler, e.g. GCC or Clang):
cc -std=c99 -Wall -Wextra -pedantic -o minish minish.c
Interactive use:
./minish
$ echo hello
hello
$ pwd
/path/to/dir
$ ls | wc -l
...
$ cd /tmp
$ exit
Script use:
cat > test.sh << 'EOF'
echo "HOME is $HOME"
pwd
echo "hello" | tr a-z A-Z > out.txt
cat out.txt
EOF
chmod +x test.sh
./minish test.sh
Or as a script interpreter:
#!/path/to/minish
echo "Running under minish"
If you want, I can help extend this with conditionals (if), loops (while, for), functions, or more accurate POSIX quoting/expansion behavior.