echo.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013-2018 K. Lange
  5. *
  6. * echo - Print arguments to stdout.
  7. *
  8. * Prints arguments to stdout, possibly interpreting escape
  9. * sequences in the arguments.
  10. */
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. void show_usage(char * argv[]) {
  15. printf(
  16. "echo - print arguments\n"
  17. "\n"
  18. "usage: %s [-ne] ARG...\n"
  19. "\n"
  20. " -n \033[3mdo not output a new line at the end\033[0m\n"
  21. " -e \033[3mprocess escape sequences\033[0m\n"
  22. " -? \033[3mshow this help text\033[0m\n"
  23. "\n", argv[0]);
  24. }
  25. int main(int argc, char ** argv) {
  26. int use_newline = 1;
  27. int process_escapes = 0;
  28. int opt;
  29. while ((opt = getopt(argc, argv, "enh?")) != -1) {
  30. switch (opt) {
  31. case '?':
  32. case 'h':
  33. show_usage(argv);
  34. return 1;
  35. case 'n':
  36. use_newline = 0;
  37. break;
  38. case 'e':
  39. process_escapes = 1;
  40. break;
  41. }
  42. }
  43. for (int i = optind; i < argc; ++i) {
  44. if (process_escapes) {
  45. for (int j = 0; j < (int)strlen(argv[i]) - 1; ++j) {
  46. if (argv[i][j] == '\\') {
  47. if (argv[i][j+1] == 'e') {
  48. argv[i][j] = '\033';
  49. for (int k = j + 1; k < (int)strlen(argv[i]); ++k) {
  50. argv[i][k] = argv[i][k+1];
  51. }
  52. }
  53. if (argv[i][j+1] == 'n') {
  54. argv[i][j] = '\n';
  55. for (int k = j + 1; k < (int)strlen(argv[i]); ++k) {
  56. argv[i][k] = argv[i][k+1];
  57. }
  58. }
  59. }
  60. }
  61. }
  62. printf("%s",argv[i]);
  63. if (i != argc - 1) {
  64. printf(" ");
  65. }
  66. }
  67. if (use_newline) {
  68. printf("\n");
  69. }
  70. fflush(stdout);
  71. return 0;
  72. }