From a80bedf135c8afbaa1ed1d04d7f24e2d0fbf6e5f Mon Sep 17 00:00:00 2001 From: Chris Cromer Date: Sat, 17 Jul 2021 22:11:11 -0400 Subject: [PATCH] make cd respect environment variables --- src/builtins.c | 63 ++++++++++++++++++++++++++++++++++++------ src/include/builtins.h | 5 ++++ 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/src/builtins.c b/src/builtins.c index 8da1578..a578edf 100644 --- a/src/builtins.c +++ b/src/builtins.c @@ -78,16 +78,49 @@ void change_directory(StringArray *args) { return; } else if (args->size == 1) { - char *cwd = get_working_directory(); - fprintf(stdout, "%s\n", cwd); - if (cwd != NULL) { - free(cwd); - cwd = NULL; - } + print_current_directory(); } else { - if (chdir(args->array[1]) != 0) { - fprintf(stderr, "cd: %s \"%s\"\n", strerror(errno), args->array[1]); + char *value = NULL; + if (args->array[1][0] == '$') { + char *variable = remove_variable_symbol(args->array[1]); + + char *array_value = get_array_list(variables, variable); + + if (array_value == NULL) { + if (variable != NULL) { + free(variable); + variable = NULL; + } + print_current_directory(); + return; + } + + value = malloc((strlen(array_value) + 1) * sizeof(char *)); + if (value == NULL) { + perror("malloc"); + exit(EXIT_FAILURE); + } + memset(value, 0, strlen(array_value) + 1); + strcpy(value, array_value); + + if (variable != NULL) { + free(variable); + variable = NULL; + } + } + else { + value = malloc((strlen(args->array[1]) + 1) * sizeof(char *)); + if (value == NULL) { + perror("malloc"); + exit(EXIT_FAILURE); + } + memset(value, 0, strlen(args->array[1]) + 1); + strcpy(value, args->array[1]); + } + + if (chdir(value) != 0) { + fprintf(stderr, "cd: %s \"%s\"\n", strerror(errno), value); } else { char *cwd = get_working_directory(); @@ -97,6 +130,20 @@ void change_directory(StringArray *args) { cwd = NULL; } } + + if (value != NULL) { + free(value); + value = NULL; + } + } +} + +void print_current_directory() { + char *cwd = get_working_directory(); + fprintf(stdout, "%s\n", cwd); + if (cwd != NULL) { + free(cwd); + cwd = NULL; } } diff --git a/src/include/builtins.h b/src/include/builtins.h index 1eeaba6..6f4b716 100644 --- a/src/include/builtins.h +++ b/src/include/builtins.h @@ -44,6 +44,11 @@ void exit_shell(StringArray *args); */ void change_directory(StringArray *args); +/** + * Print the current working directory. + */ +void print_current_directory(); + /** * Print all of the environment variables. * @param args The arguments the user input.