diff options
Diffstat (limited to '42sh/src/builtins/export.c')
| -rw-r--r-- | 42sh/src/builtins/export.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/42sh/src/builtins/export.c b/42sh/src/builtins/export.c new file mode 100644 index 0000000..358cfc7 --- /dev/null +++ b/42sh/src/builtins/export.c @@ -0,0 +1,68 @@ +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "builtins.h" +#include "utils/env.h" + +extern char **environ; + +void printenv(void) +{ + size_t i = 0; + while (environ[i] != NULL) + { + printf("export %s\n", environ[i]); + i += 1; + } +} + +void export_var(struct string *arg) +{ + char *equal = strchr(arg->data, '='); + if (equal != NULL) + { + size_t len = equal - arg->data; + char *var = malloc(len + 1); + memcpy(var, arg->data, len); + char *value = equal + 1; + var[len] = '\0'; + env_set(var, value); + free(var); + } + else + { + env_set(arg->data, ""); + } +} + +int export(struct string **args) +{ + if (args[0] == NULL) + { + printenv(); + fflush(stdout); + return 0; + } + int flagp = 0; + size_t i = 0; + if (strcmp(args[0]->data, "-p") == 0) + { + flagp = 1; + i += 1; + } + if (args[1] == NULL && flagp) + { + printenv(); + fflush(stdout); + return 0; + } + while (args[i] != NULL) + { + export_var(args[i]); + i += 1; + } + fflush(stdout); + return 0; +} |
