diff --git a/lib/sh/shquote.c b/lib/sh/shquote.c
index ecec5971..d9b11d0d 100644
--- 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);
 }
