1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <dirent.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <unistd.h>
7 #include <sys/stat.h>
8 #include <aos/cli.h>
9 #include <stdbool.h>
10 #include <path_helper.h>
11
print_help()12 static void print_help()
13 {
14 aos_cli_printf("Usage:\r\n"
15 " - To stdout:\r\n"
16 " echo \"string\"\r\n"
17 " - To file:\r\n"
18 " echo \"string\" > file\r\n");
19 }
20
21 /**
22 * Echo string to stdout or file. String must be quoted with '"' pair.
23 *
24 * echo to stdout:
25 * # echo "hello world"
26 * echo to file:
27 * # echo "hello world" > /tmp/test.txt
28 */
echo_main(int argc,char ** argv)29 static int echo_main(int argc, char **argv)
30 {
31 int fd, flag = O_CREAT | O_WRONLY, rc;
32 bool append = false;
33 char *str, *file;
34
35 /* debug use */
36 // for (int i = 0; i < argc; i++) printf("argv[%2d]: %s\r\n", i, argv[i]);
37
38 if (argc < 2 || argc > 4) {
39 print_help();
40 return -1;
41 }
42
43 str = argv[1];
44
45 if (argc == 2) {
46 /* echo to stdout */
47 printf("%s\r\n", str);
48 } else {
49 if (argv[2][0] != '>') {
50 aos_cli_printf("Error: invalid input!\r\n");
51 print_help();
52 return -1;
53 }
54
55 /* in case of 'echo "hello" >' or 'echo "hello" >>' error */
56 if ((argc == 3) && ((strlen(argv[2]) == 1) || ((strlen(argv[2]) == 2) && (argv[2][1] == '>')))) {
57 aos_cli_printf("Error: no file provided!\r\n");
58 print_help();
59 return -1;
60 }
61
62 if (argv[2][1] == '>') {
63 append = true;
64 flag |= O_APPEND;
65 } else {
66 flag |= O_TRUNC;
67 }
68
69 if (argc == 3) {
70 if (append)
71 file = argv[2] + 2;
72 else
73 file = argv[2] + 1;
74 } else {
75 file = argv[3];
76 }
77
78 char abspath[256] = {0};
79 file = get_realpath(file, abspath, sizeof(abspath));
80 if (!file) {
81 aos_cli_printf("Failed to get real path!\r\n");
82 return -1;
83 }
84
85 fd = open(file, flag);
86 if (fd < 0) {
87 aos_cli_printf("Failed to open file %s\r\n", file);
88 return errno;
89 }
90
91 int cnt = strlen(str);
92 while (cnt > 0) {
93 rc = write(fd, str, cnt);
94 if (rc < 0) {
95 aos_cli_printf("Failed to write to file!\r\n");
96 close(fd);
97 return errno;
98 } else {
99 cnt -= rc;
100 }
101 }
102
103 close(fd);
104 }
105
106 return 0;
107 }
108
109 ALIOS_CLI_CMD_REGISTER(echo_main, echo, echo strings);
110