echo.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. USE_ECHO(NEWTOY(echo, "^?Een[-eE]", TOYFLAG_BIN|TOYFLAG_MAYFORK|TOYFLAG_LINEBUF))
  12. config ECHO
  13. bool "echo"
  14. default y
  15. help
  16. usage: echo [-neE] [ARG...]
  17. Write each argument to stdout, one space between each, followed by a newline.
  18. -n No trailing newline
  19. -E Print escape sequences literally (default)
  20. -e Process the following escape sequences:
  21. \\ Backslash \0NNN Octal (1-3 digit) \xHH Hex (1-2 digit)
  22. \a Alert (beep/flash) \b Backspace \c Stop here (no \n)
  23. \f Form feed \n Newline \r Carriage return
  24. \t Horizontal tab \v Vertical tab
  25. */
  26. #define FOR_echo
  27. #include "toys.h"
  28. void echo_main(void)
  29. {
  30. int i = 0;
  31. char *arg, *c, out[8];
  32. while ((arg = toys.optargs[i])) {
  33. if (i++) putchar(' ');
  34. // Should we output arg verbatim?
  35. if (!FLAG(e)) {
  36. xprintf("%s", arg);
  37. continue;
  38. }
  39. // Handle -e
  40. for (c = arg; *c; ) {
  41. unsigned u;
  42. if (*c == '\\' && c[1] == 'c') return;
  43. if ((u = unescape2(&c, 1))<128) putchar(u);
  44. else printf("%.*s", (int)wcrtomb(out, u, 0), out);
  45. }
  46. }
  47. // Output "\n" if no -n
  48. if (!FLAG(n)) putchar('\n');
  49. }