fix(execution): reimplemented the builtins
This commit is contained in:
parent
8a5c589742
commit
a8b4e5d6df
3 changed files with 91 additions and 28 deletions
|
|
@ -208,9 +208,97 @@ int exec_ast_redir(struct ast_redir *redir, struct hash_map *vars)
|
|||
return ret;
|
||||
}
|
||||
|
||||
// Dummy try_builtin for linking
|
||||
static int try_builtin(char **argv)
|
||||
// --- Builtins ---
|
||||
|
||||
static int builtin_echo(char **argv)
|
||||
{
|
||||
bool newline = true;
|
||||
int i = 1;
|
||||
|
||||
if (argv[1] && strcmp(argv[1], "-n") == 0)
|
||||
{
|
||||
newline = false;
|
||||
i++;
|
||||
}
|
||||
|
||||
for (; argv[i]; i++)
|
||||
{
|
||||
printf("%s", argv[i]);
|
||||
if (argv[i + 1])
|
||||
printf(" ");
|
||||
}
|
||||
if (newline)
|
||||
printf("\n");
|
||||
|
||||
fflush(stdout);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static int builtin_true(char **argv)
|
||||
{
|
||||
(void)argv;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int builtin_false(char **argv)
|
||||
{
|
||||
(void)argv;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int builtin_exit(char **argv)
|
||||
{
|
||||
int exit_val = 0;
|
||||
if (argv[1])
|
||||
exit_val = atoi(argv[1]);
|
||||
exit(exit_val);
|
||||
return exit_val;
|
||||
}
|
||||
|
||||
|
||||
static int builtin_cd(char **argv)
|
||||
{
|
||||
const char *path = argv[1];
|
||||
if (!path)
|
||||
{
|
||||
path = getenv("HOME");
|
||||
if (!path)
|
||||
{
|
||||
fprintf(stderr, "cd: HOME not set\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (chdir(path) != 0)
|
||||
{
|
||||
perror("cd");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Tries to execute a builtin command if the command matches a builtin
|
||||
*
|
||||
* @param argv Array of command arguments
|
||||
* @return int Exit status of the builtin command, or -1 if not a builtin
|
||||
*/
|
||||
static int try_builtin(char **argv)
|
||||
{
|
||||
if (!argv || !argv[0])
|
||||
return 0;
|
||||
|
||||
if (strcmp(argv[0], "echo") == 0)
|
||||
return builtin_echo(argv);
|
||||
if (strcmp(argv[0], "true") == 0)
|
||||
return builtin_true(argv);
|
||||
if (strcmp(argv[0], "false") == 0)
|
||||
return builtin_false(argv);
|
||||
if (strcmp(argv[0], "exit") == 0)
|
||||
return builtin_exit(argv);
|
||||
if (strcmp(argv[0], "cd") == 0)
|
||||
return builtin_cd(argv);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue