forked from EugeneJoe/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcd.c
52 lines (50 loc) · 895 Bytes
/
cd.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
#include "shellheader.h"
/**
* _cd - changes current working directory to given directory
* @args: parsed command line
* @env: pointer to array of pointers to environment variables
*
* Return: Always 0
*/
int _cd(char **args, char **env)
{
char *pwd, *cwd;
int idx, status;
pwd = _getenv("PWD", env);
if (args[1] != NULL)
{
if (args[1][0] == '-')
{
cwd = _getenv("OLDPWD", env);
}
else if (args[1][0] == '$')
{
cwd = strtok(args[1], "$");
cwd = strtok(NULL, " ");
for (idx = 0; env[idx]; idx++)
if (_strncmp(env[idx], cwd, _strlen(cwd)) == 0)
cwd = _getenv(env[idx], env);
}
else
{
cwd = _strdup(args[1]);
}
}
else
{
cwd = _getenv("HOME", env);
}
status = chdir(cwd);
if (status == -1)
{
/* perror("Error :");*/
}
else
{
_setenv("OLDPWD", pwd, env);
_setenv("PWD", cwd, env);
}
free(cwd);
free(pwd);
return (status);
}