-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltins.c
104 lines (93 loc) · 1.63 KB
/
builtins.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
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
#include "main.h"
/**
* _printenv - print env variables
* @cmd: ptr to the cmd, with its args
* Return: 0 on success, -1 on failure
*/
int _printenv(char **cmd)
{
int i;
i = 0;
while (cmd && environ && environ[i])
{
_printf("%s\n", environ[i++]);
}
return (0);
}
/**
* _cd - change directory using chdir() func
* @cmd: cd cmd with args
* Return: 0 on success, -1 otherwise
*/
int _cd(char **cmd)
{
char buf[1024], *ptr;
char oldpwd[500], *ptroldpwd;
char *tmp = NULL;
ptroldpwd = getcwd(oldpwd, 500);
tmp = _strdup(cmd[1]);
if (!tmp || _strcmp(tmp, "~") == 0)
{
free(tmp);
tmp = _getenv("HOME");
}
else if (_strcmp(tmp, "-") == 0)
{
free(tmp);
tmp = _getenv("OLDPWD");
}
if (!tmp)
tmp = _strdup(ptroldpwd);
if (chdir(tmp) != 0)
{
free(tmp);
return (-1);
}
else
{
ptr = getcwd(buf, 1024);
setenv("PWD", ptr, 1);
setenv("OLDPWD", ptroldpwd, 1);
if (_strcmp(cmd[1], "-") == 0)
_printf("%s\n", tmp);
}
free(tmp);
return (0);
}
/**
* _exitsh - exit the shell or any,
* @cmd: the exit cmd with args, code
* Return: -1 on failure
*/
int _exitsh(char **cmd)
{
int code = 0;
if (cmd[1])
{
if (isdigit(cmd[1][0]) != 0 || atoi(cmd[1]) > 0)
code = atoi(cmd[1]);
else
return (-1);
}
return (code);
}
/**
* _setenv - set an env var
* @cmd: toks with cmd typed
* Return: -1 on failure, 0 on success
*/
int _setenv(char **cmd)
{
if (!cmd[1] || !cmd[2])
return (setenv("", "", 1));
return (setenv(cmd[1], cmd[2], 1));
}
/**
* _unsetenv - unset an env var
* @cmd: toks with cmd typed
* Return: -1 on failure, 0 on success
*/
int _unsetenv(char **cmd)
{
return (unsetenv(cmd[1]));
}