commit: 9803c587725d4bbbf6781d7268fe3682a4feb151
parent 238ef549ea87eb21e701eeff6da6640f6562ac91
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Fri, 23 Aug 2024 06:26:36 +0200
cmd/{echo,yes}: correctly handle empty string arguments
Diffstat:
3 files changed, 36 insertions(+), 17 deletions(-)
diff --git a/cmd/echo.c b/cmd/echo.c
@@ -27,12 +27,8 @@ main(int argc, char *argv[])
for(int i = 0; i < argc; i++)
{
size_t len = strlen(argv[i]);
-
- if(len > 0)
- {
- argv[i][len] = (i + 1) == argc ? '\n' : ' ';
- arg_len += len + 1; // str + space|newline
- }
+ argv[i][len] = ' ';
+ arg_len += len + 1; // str + space
}
if(arg_len == 0)
@@ -47,6 +43,8 @@ main(int argc, char *argv[])
return 0;
}
+ else
+ argv[0][arg_len - 1] = '\n';
if(opt_n) arg_len--; // no newline
diff --git a/cmd/yes.c b/cmd/yes.c
@@ -15,21 +15,27 @@ main(int argc, char *argv[])
argv++;
argc--;
- for(int i = 0; i < argc; i++)
+ if(argc == 0)
{
- size_t len = strlen(argv[i]);
-
- if(len > 0)
+ *argv = "y\n";
+ arg_len = 2;
+ }
+ else
+ {
+ for(int i = 0; i < argc; i++)
{
- argv[i][len] = (i + 1) == argc ? '\n' : ' ';
- arg_len += len + 1; // str + space|newline
+ size_t len = strlen(argv[i]);
+ argv[i][len] = ' ';
+ arg_len += len + 1; // str + space
}
- }
- if(arg_len == 0)
- {
- *argv = "y\n";
- arg_len = 2;
+ if(arg_len == 0)
+ {
+ *argv = "\n";
+ arg_len = 1;
+ }
+ else
+ argv[0][arg_len - 1] = '\n';
}
while(fwrite(*argv, arg_len, 1, stdout) == 1)
diff --git a/test-cmd/yes.t b/test-cmd/yes.t
@@ -15,6 +15,21 @@
foo
foo
foo
+ $ yes "" | head -n 5
+
+
+
+
+
+
+ $ yes foo '' | head -n 6
+ foo
+ foo
+ foo
+ foo
+ foo
+ foo
+
$ yes "$(printf 'foo\nbar')" | head -n 4
foo
bar