A simple shell implemented with abstract syntax tree written in pure C with GNU extensions.
This project is not intended to be a full-featured shell, but rather a simple shell with a simple AST implementation. Note that many features are missing, and the code may crash or behave unexpectedly. Please use it as a learning resource only.
The ast_parse_command() function is responsible for parsing the input string and building the AST. The input string is scanned in the following order:
- If the input string is empty, return
NULL. - If the input string contains
;or&, allocate aAST_LIST, split the input string into two parts and parse each part separately. - If the input string contains
&&or||, allocate aAST_LIST, split the input string and parse it. - If the input string contains
|, allocate aAST_PIPE, split the input string and parse it. - If the input string contains
<,>,<<or>>, allocate aAST_REDIRECTION, parse the left side as command and right side as a file. - If the input string contains
"or', allocate aAST_LITERAL, parse the quoted content as literals. - Tokenize remaining string with
<space>, allocate aAST_COMMAND, and parse as command followed by arguments.argc>= 1arguments[0]is not defined.arguments[n], 1 >= n > argc are pointers toAST_ARGUMENT.AST_ARGUMENTshould always to be leaf nodes.
The ast_print() and ast_free() will dump the content (to stdout) and free the AST, respectively.
The execution() function accepts a AST and executes it.
AST_COMMANDfork()(if not forked) andexecvpe()the command withAST_ARGUMENTS.AST_ARGUMENTSshould not be passed into this function.AST_LISTfork()and calls theexecution()function.waitpid()if specified.AST_PIPEopen pipes,fork()and calls theexecution().- Other tags are not implemented.
The shell checks if a function by passing argv[0] to scan_builtin(). If the executable match a builtin command, run_builtin() is called and builtin is executed.
byeorexitexits the shell.cdwraps thechdir()function.envdumps theextern char **environto stdout.pathsets thePATHenvironment variable. Parameters are separated by space.
makeor
make devFor verbose output and printing AST by default.
Abstract Syntax Tree: An Example in C for the nice example and base Tagged union AST implementation.