Skip to content

Commit

Permalink
subprocess: add a function to shell quote a single string
Browse files Browse the repository at this point in the history
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 9580353
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions subprocess/subprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 9580353

Please sign in to comment.