Skip to content
Permalink
Browse files

subprocess: add a function to shell quote a single string

We currently have a function to shell quote a list of strings, but in
some cases we may want to just quote a single string.  To avoid the
complexity of having to create a bunch of temporaries and then index out
the result, create a function that shell quotes just a single string.
  • Loading branch information...
bk2204 committed Sep 14, 2018
1 parent 912891d commit 9580353dca4d4a46dff902318a6322e1fb3564c2
Showing with 10 additions and 6 deletions.
  1. +10 −6 subprocess/subprocess.go
@@ -86,18 +86,22 @@ func Output(cmd *Cmd) (string, error) {

var shellWordRe = regexp.MustCompile(`\A[A-Za-z0-9_@/.-]+\z`)

// ShellQuoteSingle returns a string which is quoted suitably for sh.
func ShellQuoteSingle(str string) string {
// Quote anything that looks slightly complicated.
if shellWordRe.FindStringIndex(str) == nil {
return "'" + strings.Replace(str, "'", "'\\''", -1) + "'"
}
return str
}

// ShellQuote returns a copied string slice where each element is quoted
// suitably for sh.
func ShellQuote(strs []string) []string {
dup := make([]string, 0, len(strs))

for _, str := range strs {
// Quote anything that looks slightly complicated.
if shellWordRe.FindStringIndex(str) == nil {
dup = append(dup, "'"+strings.Replace(str, "'", "'\\''", -1)+"'")
} else {
dup = append(dup, str)
}
dup = append(dup, ShellQuoteSingle(str))
}
return dup
}

0 comments on commit 9580353

Please sign in to comment.
You can’t perform that action at this time.