blob: 5feb98994e0247b5cd7f0c6f440abea4e06d7adc [file] [log] [blame]
Rob Landley28964802008-01-19 17:08:39 -06001/* vi: set sw=4 ts=4:
2 *
Rob Landley3ec53ce2007-01-20 21:32:47 -05003 * echo.c - echo supporting -n and -e.
Rob Landleyfece5cb2007-12-03 20:05:57 -06004 *
Rob Landley28964802008-01-19 17:08:39 -06005 * Copyright 2007 Rob Landley <rob@landley.net>
6 *
Rob Landley5c67e352007-12-11 15:41:31 -06007 * See http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html
Rob Landley28964802008-01-19 17:08:39 -06008
Rob Landleyb1487dc2008-06-26 22:48:43 -05009USE_ECHO(NEWTOY(echo, "^?en", TOYFLAG_BIN))
Rob Landley55928b12008-01-19 17:43:27 -060010
Rob Landley28964802008-01-19 17:08:39 -060011config 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.
Rob Landley1a221d92008-05-17 17:13:26 -050021 -e Process the following escape sequences:
22 \\ backslash
23 \a alert (beep/flash)
24 \b backspace
25 \c Stop output here (avoids trailing newline)
26 \f form feed
27 \n newline
28 \r carriage return
29 \t horizontal tab
30 \v vertical tab
Rob Landley28964802008-01-19 17:08:39 -060031*/
Rob Landley3ec53ce2007-01-20 21:32:47 -050032
33#include "toys.h"
34
Rob Landleyefda21c2007-11-29 18:14:37 -060035void echo_main(void)
Rob Landley3ec53ce2007-01-20 21:32:47 -050036{
37 int i = 0;
38 char *arg, *from = "\\abfnrtv", *to = "\\\a\b\f\n\r\t\v";
Rob Landley2c226852007-11-15 18:30:30 -060039
Rob Landley3ec53ce2007-01-20 21:32:47 -050040 for (;;) {
41 arg = toys.optargs[i];
42 if (!arg) break;
43 if (i++) xputc(' ');
Rob Landley452ff9e2007-01-20 22:41:29 -050044
45 // Handle -e
Rob Landley2c226852007-11-15 18:30:30 -060046
Rob Landley3ec53ce2007-01-20 21:32:47 -050047 if (toys.optflags&2) {
48 int c, j = 0;
49 for (;;) {
50 c = arg[j++];
51 if (!c) break;
52 if (c == '\\') {
53 char *found;
54 int d = arg[j++];
55
Rob Landley452ff9e2007-01-20 22:41:29 -050056 // handle \escapes
Rob Landley3ec53ce2007-01-20 21:32:47 -050057
58 if (d) {
59 found = strchr(from, d);
60 if (found) c = to[found-from];
61 else if (d == 'c') goto done;
62 else if (d == '0') {
63 c = 0;
64 while (arg[j]>='0' && arg[j]<='7')
65 c = (c*8)+arg[j++]-'0';
66 }
Rob Landley3ec53ce2007-01-20 21:32:47 -050067 }
68 }
69 xputc(c);
70 }
Rob Landley3ec53ce2007-01-20 21:32:47 -050071 } else xprintf("%s", arg);
72 }
Rob Landley452ff9e2007-01-20 22:41:29 -050073
Rob Landley3ec53ce2007-01-20 21:32:47 -050074 // Output "\n" if no -n
75 if (!(toys.optflags&1)) xputc('\n');
76done:
77 xflush();
Rob Landley3ec53ce2007-01-20 21:32:47 -050078}