-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo.c
86 lines (71 loc) · 2.01 KB
/
echo.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
#include <stdio.h> // printf
#include <string.h> // strlen
#include <stdlib.h>
void exec_echo(char **arg)
{ // to do : handle the case when commas are not closed
char * str = (char *) calloc(10 * 1024, sizeof(char));
if(str == NULL)
{
perror("");
return;
}
for(int i=1; arg[i] != NULL; i++)
{
strcat(str, arg[i]);
strcat(str, " ");
}
int flag_s_comma = 0, flag_d_comma = 0, flag_b_slash = 0;
for (int i = 0; i < (int)strlen(str); i++)
{ // to do : what if echo \0advasdf ?
// to print env var
if(str[i] == '$')
{
i++;
// get name of env var
char var[32] = "\0";
for(int j= 0; str[i] != ' ' && str[i] != '\t' && str[i] != '\0' && str[i] != '\n'; j++, i++)
{
var[j] = str[i];
}
// str[i] is not yet traversed
i--;
printf("%s", getenv(var));
}
// characters inside single inverted comma; printed as is
else if (flag_s_comma)
{
if (str[i] == '\'')
flag_s_comma = 0;
else
printf("%c", str[i]);
}
// characters inside double inverted comma; printed as is
else if (flag_d_comma)
{
if (str[i] == '"')
flag_d_comma = 0;
else
printf("%c", str[i]);
}
// character trailing back slash; devoid of special meaning
else if (flag_b_slash)
{
printf("%c", str[i]);
flag_b_slash = 0;
}
// nothing special
else
{
if (str[i] == '\'')
flag_s_comma = 1;
else if (str[i] == '"')
flag_d_comma = 1;
else if (str[i] == '\\') // '\\' is '\' : extra backslash is to escape itself !
flag_b_slash = 1;
else
printf("%c", str[i]);
}
}
free(str);
printf("\n");
}