summaryrefslogtreecommitdiff
path: root/src/commands/echo.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/commands/echo.c')
-rw-r--r--src/commands/echo.c103
1 files changed, 103 insertions, 0 deletions
diff --git a/src/commands/echo.c b/src/commands/echo.c
new file mode 100644
index 0000000..b80f872
--- /dev/null
+++ b/src/commands/echo.c
@@ -0,0 +1,103 @@
+#include "../command.h"
+
+#include <stdio.h>
+#include <string.h>
+
+static void print_with_escape_codes(const char* str) {
+
+ size_t index = 0;
+ while (true) {
+ char c = str[index];
+ index++;
+
+ if (c == '\0') break;
+ if (c != '\\') {
+ putchar(c);
+ continue;
+ }
+
+ char n = str[index];
+ index++;
+
+ switch (n) {
+ case '\\':
+ putchar('\\');
+ break;
+ case 'b':
+ putchar('\b');
+ break;
+ case 'c':
+ exit(EXIT_SUCCESS);
+ case 'n':
+ putchar('\n');
+ break;
+ case 'r':
+ putchar('\r');
+ break;
+ case 't':
+ putchar('\t');
+ break;
+ case 'v':
+ putchar('\v');
+ break;
+ default:
+ putchar(c);
+ putchar(n);
+ }
+ }
+}
+
+COMMAND(echo) {
+
+ if (argc < 1) {
+ return EXIT_SUCCESS;
+ }
+
+ bool escape_codes = false;
+ bool newline = true;
+
+ int start = 0;
+
+ if (prefix("-", argv[0])) {
+
+ start = 1;
+
+ for (size_t i = 0; i < strlen(argv[0] + 1); i++) {
+ char c = argv[0][i + 1];
+ switch (c) {
+ case 'e':
+ escape_codes = true;
+ break;
+ case 'E':
+ escape_codes = false;
+ break;
+ case 'n':
+ newline = false;
+ break;
+ default:
+ escape_codes = false;
+ newline = true;
+ start = 0;
+ break;
+ }
+ }
+ }
+
+ for (int i = start; i < argc; i++) {
+ if (escape_codes) {
+ print_with_escape_codes(argv[i]);
+ } else {
+ printf("%s", argv[i]);
+ }
+
+ if (i + 1 != argc) {
+ putchar(' ');
+ }
+ }
+
+ if (newline) {
+ putchar('\n');
+ }
+
+ return EXIT_SUCCESS;
+}