This repository has been archived by the owner on May 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtin_export.c
79 lines (68 loc) · 1.69 KB
/
builtin_export.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "builtin.h"
extern char **environ;
extern int optind;
int builtin_export(int argc, char *argv[])
{
char *PROGNAME = argv[0];
int print = 0;
int addition = 1;
int opt;
while ((opt = getopt(argc, argv, "pr")) != -1) {
switch (opt) {
case 'p':
print = 1;
break;
case 'r':
addition = -1;
break;
default: /* ? */
goto ERROR;
}
}
argc -= optind;
argv += optind;
if (print) {
int environ_length = 0;
while (environ[environ_length]) {
environ_length++;
}
int i = addition == 1 ? 0 : environ_length - 1;
int last = addition == 1 ? environ_length : -1;
for (; i != last; i += addition) {
printf("%s\n", environ[i]);
}
goto SUCCESS;
}
for (; *argv; argv++) {
char *c;
if ((c = strchr(*argv, '=')) == NULL) {
if (setenv(*argv, "", 0) == -1) {
perror(PROGNAME);
goto ERROR;
}
} else {
if (c == *argv) {
fprintf(stderr, "%s: Invalid argument\n", PROGNAME);
goto ERROR;
}
char *name = strndup(*argv, c - *argv);
char *value = strdup(*(c + 1) == '\0' ? "" : c + 1);
if (setenv(name, value, 1) == -1) {
perror(PROGNAME);
goto ERROR;
}
free(name);
free(value);
}
}
SUCCESS:
optind = 1;
return 0;
ERROR:
optind = 1;
return -1;
}