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

2017-10-31 Thread Clark Wang
On Mon, Oct 30, 2017 at 10:41 PM, Chet Ramey  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);
 }


sh_single_quote.patch
Description: Binary data


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

2017-10-31 Thread Clark Wang
On Tue, Oct 31, 2017 at 3:25 PM, Clark Wang  wrote:

> On Mon, Oct 30, 2017 at 10:41 PM, Chet Ramey  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.
>

Updated by dealing with empty strings (and malloc'ing 2 more bytes) though
I'm not sure if it's necessary since the func sh_quote_reusable() already
handles empty strings.


sh_single_quote.patch
Description: Binary data