-
Notifications
You must be signed in to change notification settings - Fork 0
/
built_in_cmds.c
106 lines (92 loc) · 1.7 KB
/
built_in_cmds.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
105
#include "shell.h"
/**
* print_env - Prints the environment variables
* @env: Arguments
*/
void print_env(char **env)
{
while (*env != NULL)
{
write(1, *env, strlen(*env));
write(1, "\n", 1);
env++;
}
}
/**
* handle_exit - Handles the exit functionality
* @input: Input value to handle
* @exit_status: Exit status of the code
*/
void handle_exit(char *input, int exit_status)
{
free(input);
exit(exit_status);
}
/**
* shell_exit - Handles the exit status
* @args: Arguments to the function
* @input: Checks the status of exit
*
* Return: Status of exit, 1 if otherwise
*/
int shell_exit(char **args, char *input)
{
char *status_str;
int exit_status, i;
if (args[1] != NULL)
{
exit_status = 0;
status_str = args[1];
for (i = 0; status_str[i] != '\0'; i++)
{
if (status_str[i] < '0' || status_str[i] > '9')
{
handle_exit(input, 2);
return (1);
}
exit_status = exit_status * 10 + (status_str[i] - '0');
}
handle_exit(input, exit_status);
}
else
{
handle_exit(input, 127);
}
return (1);
}
/**
* handle_cd - Handles the cd functionality
* @args: Array of commands
* @num_args: Argument count
*/
void handle_cd(char **args, int num_args)
{
const char *home_dir, *prev_dir;
home_dir = getenv("HOME");
prev_dir = getenv("OLDPWD");
if (num_args == 1 || strcmp(args[1], "~") == 0)
{
if (!home_dir)
{
perror("Home environment not set");
return;
}
if (chdir(home_dir) != 0)
perror("cd");
}
else if (num_args == 2 && strcmp(args[1], "-") == 0)
{
if (!prev_dir)
{
perror("OLDPWD environment not set");
return;
}
if (chdir(prev_dir) != 0)
perror("cd");
}
else
{
if (chdir(args[1]) != 0)
perror("cd");
}
}