-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_builtins.c
More file actions
130 lines (110 loc) · 2.34 KB
/
shell_builtins.c
File metadata and controls
130 lines (110 loc) · 2.34 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "main.h"
/**
* _exit - exits the terminal
* @args: arrays of arguments to clear before exiting
*/
void _exiting(char **args) {
/* Declare variables */
int i, status;
/* Initialize n with 0 */
status = 0;
/* Check if there is at least one argument */
if (args[1]) {
status = atoi(args[1]);
if (status <= -1)
status = 2;
for (i = 0; args[i]; i++)
free(args[i]);
}
free(args);
exit(status);
}
/**
* my_atoi - converts character c to integer datatype
* @c: character to convert
* Return: converted integer
*/
int my_atoi(char *c) {
/* Variable declarations */
int i, my_int, sign;
/* variable initialization */
i = 0;
my_int = 0;
sign = 1;
/* Skip leading non-digit characters */
while (c[i] != '\0' && !(c[i] >= '0' && c[i] <= '9')) {
if (c[i] == '-') {
sign *= -1;
}
i++;
}
/* Convert digits to integer */
while (c[i] >= '0' && c[i] <= '9') {
my_int = my_int * 10 + (c[i] - '0');
i++;
}
return (my_int * sign);
}
/**
* _env - prints current environment
* @args: arguments array
*/
void _env(char **args __attribute__ ((unused))) {
int i;
/* Print the environment variable followed by a newline */
for (i = 0; environ[i]; i++) {
_puts(environ[i]);
}
}
/**
* _setenv - sets or updates environmental variables
* @args: argument arrays
*/
void _setenv(char **args) {
int i, j, k, length;
if (!args[1] || !args[2]) {
perror(_getenv("_"));
return;
}
for (i = 0; environ[i]; i++) {
j = 0;
if (strncmp(args[1], environ[i], strlen(args[1])) == 0) {
k = 0;
while (args[2][k]) {
environ[i][j + 1 + k] = args[2][k];
k++;
}
environ[i][j + 1 + k] = '\0';
return;
}
}
if (!environ[i]) {
printf("Adding new environment variable: %s=%s\n", args[1], args[2]);
length = strlen(args[1]) + strlen(args[2]) + 2;
environ[i] = (char *) malloc(length * sizeof(char));
snprintf(environ[i], length, "%s=%s", args[1], args[2]);
environ[i + 1] = NULL;
}
}
/**
* _unsetenv - removes environmental variable if it exists
* @args: arguments array
*/
void _unsetenv(char **args) {
int i;
if (!args[1]) {
puts("Error: No argument provided.");
return;
}
for (i = 0; environ[i]; i++) {
if (_strncmp(args[1], environ[i], strlen(args[1])) == 0) {
free(environ[i]);
while (environ[i + 1]) {
environ[i] = environ[i + 1];
i++;
}
environ[i] = NULL;
return;
}
}
}