Skip to contentSkip to conversation

builtin: Fix 'echo --' handling

PATCH In review Mihail Konev 2 participants 2 messages Dec 18, 2016

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 builtin: Fix 'echo --' handling

Ignore first "--", as the end of options.

Breaks uses that expect 'echo' to output arguments verbatim, but fixes those that expect 'echo --' to do so (such as 'echo -- -n').

---
 src/bltin/printf.c | 23 ++++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)
src/bltin/printf.c +16 -7
index a626cee2c60e..1b3df313f02d 100644
@@ -450,20 +450,29 @@ int
 echocmd(int argc, char **argv)
 {
 	int nonl;
+	int dashdash_met = 0;
 
-	nonl = *++argv ? equal(*argv, "-n") : 0;
+	nonl = (*++argv && !dashdash_met) ? equal(*argv, "-n") : 0;
 	argv += nonl;
 
 	do {
-		int c;
-
-		if (likely(*argv))
-			nonl += print_escape_str("%s", NULL, NULL, *argv++);
+		int c = 1;
+
+		if (likely(*argv)) {
+			if (unlikely(equal(*argv, "--") && !dashdash_met)) {
+				dashdash_met = 1;
+				c = 0;
+			} else
+				nonl += print_escape_str("%s", NULL, NULL, *argv);
+			argv++;
+		}
 		if (likely((nonl + !*argv) > 1))
 			break;
 
-		c = *argv ? ' ' : '\n';
-		out1c(c);
+		if (c) {
+			c = *argv ? ' ' : '\n';
+			out1c(c);
+		}
 	} while (*argv);
 	return 0;
 }
Signature · 1 line
2.9.2
#1 lore raw
Quoted 1 line · Mihail Konev

Ignore first "--", as the end of options.

echo -- is required by POSIX to print --. To quote:

Quoted 1 line

The echo utility shall not recognize the "--" argument in the manner specified by Guideline 10 of XBD Utility Syntax Guidelines; "--" shall be recognized as a string operand.

Scripts wishing to print the text "-n" without anything else must find some other way, for example using the printf command.

Cheers,
Harald van Dijk