comparison toys/posix/echo.c @ 653:2986aa63a021

Move commands into "posix", "lsb", and "other" menus/directories.
author Rob Landley <rob@landley.net>
date Sat, 25 Aug 2012 14:25:22 -0500
parents toys/echo.c@b24c4fe9f4fd
children 6df4ccc0acbe
comparison
equal deleted inserted replaced
652:2d7c56913fda 653:2986aa63a021
1 /* vi: set sw=4 ts=4:
2 *
3 * echo.c - echo supporting -n and -e.
4 *
5 * Copyright 2007 Rob Landley <rob@landley.net>
6 *
7 * See http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html
8
9 USE_ECHO(NEWTOY(echo, "^?en", TOYFLAG_BIN))
10
11 config ECHO
12 bool "echo"
13 default y
14 help
15 usage: echo [-ne] [args...]
16
17 Write each argument to stdout, with one space between each, followed
18 by a newline.
19
20 -n No trailing newline.
21 -e Process the following escape sequences:
22 \\ backslash
23 \0NNN octal values (1 to 3 digits)
24 \a alert (beep/flash)
25 \b backspace
26 \c stop output here (avoids trailing newline)
27 \f form feed
28 \n newline
29 \r carriage return
30 \t horizontal tab
31 \v vertical tab
32 \xHH hexadecimal values (1 to 2 digits)
33 */
34
35 #define THIS echo
36 #include "toys.h"
37
38 #define FLAG_e (1<<1)
39 #define FLAG_n (1<<0)
40
41 void echo_main(void)
42 {
43 int i = 0, out;
44 char *arg, *from = "\\abfnrtv", *to = "\\\a\b\f\n\r\t\v", *c;
45
46 for (;;) {
47 arg = toys.optargs[i];
48 if (!arg) break;
49 if (i++) xputc(' ');
50
51 // Should we output arg verbatim?
52
53 if (!(toys.optflags&FLAG_e)) {
54 xprintf("%s", arg);
55 continue;
56 }
57
58 // Handle -e
59
60 for (c=arg;;) {
61 if (!(out = *(c++))) break;
62
63 // handle \escapes
64 if (out == '\\' && *c) {
65 int n = 0, slash = *(c++);
66 char *found = strchr(from, slash);
67 if (found) out = to[found-from];
68 else if (slash == 'c') goto done;
69 else if (slash == '0') {
70 out = 0;
71 while (*c>='0' && *c<='7' && n++<3)
72 out = (out*8)+*(c++)-'0';
73 } else if (slash == 'x') {
74 out = 0;
75 while (n++<2) {
76 if (*c>='0' && *c<='9')
77 out = (out*16)+*(c++)-'0';
78 else {
79 int temp = tolower(*c);
80 if (temp>='a' && temp<='f') {
81 out = (out*16)+temp-'a'+10;
82 c++;
83 } else break;
84 }
85 }
86 // Slash in front of unknown character, print literal.
87 } else c--;
88 }
89 xputc(out);
90 }
91 }
92
93 // Output "\n" if no -n
94 if (!(toys.optflags&FLAG_n)) xputc('\n');
95 done:
96 xflush();
97 }