-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuitins.c
More file actions
92 lines (75 loc) · 1.51 KB
/
buitins.c
File metadata and controls
92 lines (75 loc) · 1.51 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
#include "main.h"
/**
* change_dir - changes the current directory
*
* @argv: a list of argument
*/
void change_dir(char **argv)
{
const char *dir = argv[1];
if (dir == NULL || strcmp(dir, "~") == 0)
dir = _getenv("HOME");
else if (strcmp(dir, "-") == 0)
dir = _getenv("OLDPWD");
if (chdir(dir) == -1)
perror("chdir");
else
setenv("PWD", dir, 1);
}
/**
* print_env - prints the current environment
*/
void print_env(void)
{
char **env = environ;
while (*env != NULL)
{
printf("%s\n", *env);
env++;
}
}
/**
* _getenv - returns a specific environment variable
* @var_name: the name of the variable
* Return: a pointer to the environment variable
*/
char *_getenv(char *var_name)
{
size_t var_len = _strlen(var_name);
char **env;
if (var_name == NULL || environ == NULL)
return (NULL);
for (env = environ; *env != NULL; env++)
{
if (_strncmp(var_name, *env, var_len) == 0 &&
(*env)[var_len] == '=')
return (&(*env)[var_len + 1]);
}
return (NULL);
}
/**
* set_env - creates or updates an environment variable
* @argv: a list of arguments
*/
void set_env(char **argv)
{
char *name = argv[1];
char *value = argv[2] == NULL ? " " : argv[2];
if (setenv(name, value, 1) == -1)
perror("Invalid command");
}
/**
* unset_env - unset an environment variable
* * @argv: a list of arguments
*/
void unset_env(char **argv)
{
char *name = argv[1];
if (name == NULL)
{
perror("unset: not enough arguments");
return;
}
if (unsetenv(name) == -1)
perror("an error accured");
}