1 /* echo.c - echo supporting -n and -e.
2 *
3 * Copyright 2007 Rob Landley <rob@landley.net>
4 *
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/echo.html
6 *
7 * Deviations from posix: we parse command line options, as Linux has
8 * consistently done since 1992. Posix defaults -e to on, we require -e.
9 * We also honor -- to _stop_ option parsing (bash doesn't, we go with
10 * consistency over compatibility here).
11
12 USE_ECHO(NEWTOY(echo, "^?Een[-eE]", TOYFLAG_BIN|TOYFLAG_MAYFORK|TOYFLAG_LINEBUF))
13
14 config ECHO
15 bool "echo"
16 default y
17 help
18 usage: echo [-neE] [ARG...]
19
20 Write each argument to stdout, one space between each, followed by a newline.
21
22 -n No trailing newline
23 -E Print escape sequences literally (default)
24 -e Process the following escape sequences:
25 \\ Backslash \0NNN Octal (1-3 digit) \xHH Hex (1-2 digit)
26 \a Alert (beep/flash) \b Backspace \c Stop here (no \n)
27 \f Form feed \n Newline \r Carriage return
28 \t Horizontal tab \v Vertical tab
29 */
30
31 #define FOR_echo
32 #include "toys.h"
33
echo_main(void)34 void echo_main(void)
35 {
36 int i = 0;
37 char *arg, *c, out[8];
38
39 while ((arg = toys.optargs[i])) {
40 if (i++) putchar(' ');
41
42 // Should we output arg verbatim?
43
44 if (!FLAG(e)) {
45 xprintf("%s", arg);
46 continue;
47 }
48
49 // Handle -e
50
51 for (c = arg; *c; ) {
52 unsigned u;
53
54 if (*c == '\\' && c[1] == 'c') return;
55 if ((u = unescape2(&c, 1))<128) putchar(u);
56 else printf("%.*s", (int)wcrtomb(out, u, 0), out);
57 }
58 }
59
60 // Output "\n" if no -n
61 if (!FLAG(n)) putchar('\n');
62 }
63