Skip to content

Commit

Permalink
sys/shell: add shell_parse_file()
Browse files Browse the repository at this point in the history
  • Loading branch information
benpicco committed May 7, 2024
1 parent 1bfae43 commit 55942bb
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
14 changes: 14 additions & 0 deletions sys/include/shell.h
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,20 @@ static inline void shell_run(const shell_command_t *commands,
*/
int shell_handle_input_line(const shell_command_t *commands, char *line);

/**
* @brief Read shell commands from a file and run them.
*
* @note This requires the `vfs` module.
*
* @param[in] commands ptr to array of command structs
* @param[in] filename file to read shell commands from
*
* @returns 0 if all commands were executed successful
* error return of failed command otherwise
*/
int shell_parse_file(const shell_command_t *commands,
const char *filename);

#ifndef __cplusplus
/**
* @brief Define shell command
Expand Down
35 changes: 35 additions & 0 deletions sys/shell/shell.c
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@
#include "shell.h"
#include "shell_lock.h"

#ifdef MODULE_VFS
#include <fcntl.h>
#include "vfs.h"
#endif

/* define shell command cross file array */
XFA_INIT_CONST(shell_command_xfa_t*, shell_commands_xfa);

Expand Down Expand Up @@ -529,3 +534,33 @@ void shell_run_once(const shell_command_t *shell_commands,
print_prompt();
}
}

#ifdef MODULE_VFS
int shell_parse_file(const shell_command_t *shell_commands,
const char *filename)
{
char buffer[SHELL_DEFAULT_BUFSIZE];

int fd = vfs_open(filename, O_RDONLY, 0);
if (fd < 0) {
printf("Can't open %s\n", filename);
return fd;
}

int res = 0;
while (vfs_readline(fd, buffer, sizeof(buffer)) > 0) {
/* skip comment lines */
if (buffer[0] == '#') {
continue;
}
res = shell_handle_input_line(shell_commands, buffer);
if (res) {
break;
}
}

vfs_close(fd);

return 0;
}
#endif

0 comments on commit 55942bb

Please sign in to comment.