bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: remove empty '' in ${var@Q} result?


From: Clark Wang
Subject: Re: remove empty '' in ${var@Q} result?
Date: Tue, 31 Oct 2017 15:25:12 +0800

On Mon, Oct 30, 2017 at 10:41 PM, Chet Ramey <chet.ramey@case.edu> wrote:

>
> This is an effect of using single quotes in the @Q operator. If you want
> to single-quote a string containing single quotes, this is how you do it.
>

I made a patch (also attached). Please see if it's ok.

Tested with arr=('' a \' \'\' \'\'\' \'a a\' \'a\'a). the result will be:

arr[0]=''
arr[1]='a'
arr[2]=\'
arr[3]=\'\'
arr[4]=\'\'\'
arr[5]=\''a'
arr[6]='a'\'
arr[7]=\''a'\''a'

--- a/lib/sh/shquote.c
+++ b/lib/sh/shquote.c
@@ -98,34 +98,32 @@ sh_single_quote (string)
   register int c;
   char *result, *r;
   const char *s;
+  int left_quote_inserted = 0;

-  result = (char *)xmalloc (3 + (4 * strlen (string)));
+  result = (char *)xmalloc (1 + (3 * strlen (string)));
   r = result;

-  if (string[0] == '\'' && string[1] == 0)
-    {
-      *r++ = '\\';
-      *r++ = '\'';
-      *r++ = 0;
-      return result;
-    }
-
-  *r++ = '\'';
-
   for (s = string; s && (c = *s); s++)
     {
-      *r++ = c;
-
-      if (c == '\'')
-       {
-         *r++ = '\\';  /* insert escaped single quote */
+      if (c == '\'') {
+       if (left_quote_inserted) {
+         *r++ = '\'';
+         left_quote_inserted = 0;
+       }
+       *r++ = '\\';
+       *r++ = '\'';
+      } else {
+       if ( ! left_quote_inserted) {
          *r++ = '\'';
-         *r++ = '\'';  /* start new quoted string */
+         left_quote_inserted = 1;
        }
+       *r++ = c;
+      }
     }
-
-  *r++ = '\'';
-  *r = '\0';
+  if (left_quote_inserted) {
+    *r++ = '\'';
+  }
+  *r++ = 0;

   return (result);
 }

Attachment: sh_single_quote.patch
Description: Binary data


reply via email to

[Prev in Thread] Current Thread [Next in Thread]