From e8aedb0ef4f73961a98a1505527dc9ec8780a0d5 Mon Sep 17 00:00:00 2001 From: dzwdz Date: Wed, 27 Jul 2022 21:09:31 +0200 Subject: user/shell: basic shell script support --- src/user/app/shell/parser.c | 12 +++++++++++- src/user/app/shell/shell.c | 24 +++++++++++++++++------- 2 files changed, 28 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/user/app/shell/parser.c b/src/user/app/shell/parser.c index bd70350..878202d 100644 --- a/src/user/app/shell/parser.c +++ b/src/user/app/shell/parser.c @@ -13,11 +13,16 @@ static char skipspace(char **sp) { return *s; } +static bool isspecial(char c) { + return c == '>' || c == '#'; +} + static char *parg(char **sp) { char *s = *sp; char *res = NULL; if (skipspace(&s)) { + // TODO incorrectly handles strings like a"b" switch (*s) { case '"': s++; @@ -27,8 +32,13 @@ static char *parg(char **sp) { break; default: res = s; - while (*s && !isspace(*s) && *s != '>') + while (*s && !isspace(*s) && !isspecial(*s)) s++; + if (*s == '#') { + *s = '\0'; /* end parsing early */ + if (res == s) /* don't output an empty arg */ + res = NULL; + } break; } if (*s) *s++ = '\0'; diff --git a/src/user/app/shell/shell.c b/src/user/app/shell/shell.c index e1514d9..995ce53 100644 --- a/src/user/app/shell/shell.c +++ b/src/user/app/shell/shell.c @@ -10,11 +10,10 @@ int main(); -// TODO fgets -static int readline(char *buf, size_t max) { +static int readline(char *buf, size_t max, FILE *f) { char c = '\0'; size_t pos = 0; - while (pos < (max-1) && c != '\n' && fread(&c, 1, 1, stdin)) + while (pos < (max-1) && c != '\n' && fread(&c, 1, 1, f)) buf[pos++] = c; buf[pos++] = '\0'; return pos; @@ -111,12 +110,23 @@ static void run(char *cmd) { } -int main(void) { +int main(int argc, char **argv) { static char buf[256]; + FILE *f = stdin; + + if (argc > 1) { + f = fopen(argv[1], "r"); + if (!f) { + printf("sh: couldn't open %s\n", argv[1]); + return 1; + } + } + for (;;) { - printf("$ "); - readline(buf, 256); - if (feof(stdin)) return 0; + if (f == stdin) + printf("$ "); + readline(buf, 256, f); + if (feof(f)) return 0; run(buf); } } -- cgit v1.2.3