comparison toys/echo.c @ 508:f062652562bd

Cleanup pass, and support unrecognized slash chars ala "echo -e \p".
author Rob Landley <rob@landley.net>
date Fri, 02 Mar 2012 08:27:50 -0600
parents d8ff3b0980cf
children b24c4fe9f4fd
comparison
equal deleted inserted replaced
507:94a2905dd325 508:f062652562bd
34 34
35 #include "toys.h" 35 #include "toys.h"
36 36
37 void echo_main(void) 37 void echo_main(void)
38 { 38 {
39 int i = 0; 39 int i = 0, out;
40 char *arg, *from = "\\abfnrtv", *to = "\\\a\b\f\n\r\t\v"; 40 char *arg, *from = "\\abfnrtv", *to = "\\\a\b\f\n\r\t\v", *c;
41 41
42 for (;;) { 42 for (;;) {
43 arg = toys.optargs[i]; 43 arg = toys.optargs[i];
44 if (!arg) break; 44 if (!arg) break;
45 if (i++) xputc(' '); 45 if (i++) xputc(' ');
46 46
47 // Should we output arg verbatim?
48
49 if (!(toys.optflags&2)) {
50 xprintf("%s", arg);
51 continue;
52 }
53
47 // Handle -e 54 // Handle -e
48 55
49 if (toys.optflags&2) { 56 for (c=arg;;) {
50 int c, j = 0; 57 if (!(out = *(c++))) break;
51 for (;;) {
52 c = arg[j++];
53 if (!c) break;
54 if (c == '\\') {
55 char *found;
56 int d = arg[j++];
57 58
58 // handle \escapes 59 // handle \escapes
59 60 if (out == '\\' && *c) {
60 if (d) { 61 int n = 0, slash = *(c++);
61 found = strchr(from, d); 62 char *found = strchr(from, slash);
62 if (found) c = to[found-from]; 63 if (found) out = to[found-from];
63 else if (d == 'c') goto done; 64 else if (slash == 'c') goto done;
64 else if (d == '0') { 65 else if (slash == '0') {
65 int n = 0; 66 out = 0;
66 c = 0; 67 while (*c>='0' && *c<='7' && n++<3)
67 while (arg[j]>='0' && arg[j]<='7' && n++<3) 68 out = (out*8)+*(c++)-'0';
68 c = (c*8)+arg[j++]-'0'; 69 } else if (slash == 'x') {
69 } else if (d == 'x') { 70 out = 0;
70 int n = 0; 71 while (n++<2) {
71 c = 0; 72 if (*c>='0' && *c<='9')
72 while (n++<2) { 73 out = (out*16)+*(c++)-'0';
73 if (arg[j]>='0' && arg[j]<='9') 74 else {
74 c = (c*16)+arg[j++]-'0'; 75 int temp = tolower(*c);
75 else { 76 if (temp>='a' && temp<='f') {
76 int temp = tolower(arg[j]); 77 out = (out*16)+temp-'a'+10;
77 if (temp>='a' && temp<='f') { 78 c++;
78 c = (c*16)+temp-'a'+10; 79 } else break;
79 j++;
80 } else break;
81 }
82 }
83 } 80 }
84 } 81 }
85 } 82 // Slash in front of unknown character, print literal.
86 xputc(c); 83 } else c--;
87 } 84 }
88 } else xprintf("%s", arg); 85 xputc(out);
86 }
89 } 87 }
90 88
91 // Output "\n" if no -n 89 // Output "\n" if no -n
92 if (!(toys.optflags&1)) xputc('\n'); 90 if (!(toys.optflags&1)) xputc('\n');
93 done: 91 done: