Browse Source

add unsetenv

K. Lange 4 years ago
parent
commit
4cde60c50e
4 changed files with 42 additions and 1 deletions
  1. 9 0
      apps/sh.c
  2. 1 0
      base/home/local/.eshrc
  3. 1 0
      base/usr/include/stdlib.h
  4. 31 1
      libc/stdlib/putenv.c

+ 9 - 0
apps/sh.c

@@ -1646,7 +1646,15 @@ uint32_t shell_cmd_not(int argc, char * argv[]) {
 	child = 0;
 	tcsetpgrp(STDIN_FILENO, getpid());
 	return !ret_code;
+}
+
+uint32_t shell_cmd_unset(int argc, char * argv[]) {
+	if (argc < 2) {
+		fprintf(stderr, "%s: expected command argument\n", argv[0]);
+		return 1;
+	}
 
+	return unsetenv(argv[1]);
 }
 
 void install_commands() {
@@ -1668,4 +1676,5 @@ void install_commands() {
 	shell_install_command("source",  shell_cmd_source, "run a shell script in the context of this shell");
 	shell_install_command("exec",    shell_cmd_exec, "replace shell (or subshell) with command");
 	shell_install_command("not",     shell_cmd_not, "invert status of command");
+	shell_install_command("unset",   shell_cmd_unset, "unset variable");
 }

+ 1 - 0
base/home/local/.eshrc

@@ -7,3 +7,4 @@ export PS1="\e]1;\u@\h:\w\\007\e]2;\u@\\h:\w\007\\e[1m\e[s\e[400C\e[16D\e[1m\e[3
 
 export-cmd START kcmdline -g start
 if equals? "$START" "--vga" then export RLINE_THEME="default" else export RLINE_THEME="sunsmoke"
+unset START

+ 1 - 0
base/usr/include/stdlib.h

@@ -18,6 +18,7 @@ extern int abs(int j);
 
 extern int putenv(char * name);
 extern int setenv(const char *name, const char *value, int overwrite);
+extern int unsetenv(const char * str);
 
 extern double strtod(const char *nptr, char **endptr);
 extern double atof(const char * nptr);

+ 31 - 1
libc/stdlib/putenv.c

@@ -14,6 +14,36 @@ static int why_no_strnstr(char * a, char * b, int n) {
 	return 0;
 }
 
+int unsetenv(const char * str) {
+	int last_index = -1;
+	int found_index = -1;
+	int len = strlen(str);
+
+	for (int i = 0; environ[i]; ++i) {
+		if (found_index == -1 && (strstr(environ[i], str) == environ[i] && environ[i][len] == '=')) {
+			found_index = i;
+		}
+		last_index = i;
+	}
+
+	if (found_index == -1) {
+		/* not found = success */
+		return 0;
+	}
+
+	if (last_index == found_index) {
+		/* Was last element */
+		environ[last_index] = NULL;
+		return 0;
+	}
+
+	/* Was not last element, swap ordering */
+	environ[found_index] = environ[last_index];
+	environ[last_index] = NULL;
+	return 0;
+}
+
+
 int putenv(char * string) {
 	char name[strlen(string)];
 	strcpy(name, string);
@@ -27,7 +57,7 @@ int putenv(char * string) {
 
 	int i;
 	for (i = 0; i < (_environ_size - 1) && environ[i]; ++i) {
-		if (!why_no_strnstr(name, environ[i], s)) {
+		if (!why_no_strnstr(name, environ[i], s) && environ[i][s] == '=') {
 			environ[i] = string;
 			return 0;
 		}