github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/cmd/roachprod/ssh/shell.go (about)

     1  // Copyright 2018 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package ssh
    12  
    13  import (
    14  	"fmt"
    15  	"regexp"
    16  	"strings"
    17  )
    18  
    19  const shellMetachars = "|&;()<> \t\n$\\`"
    20  
    21  // Escape1 TODO(peter): document
    22  func Escape1(arg string) string {
    23  	if strings.ContainsAny(arg, shellMetachars) {
    24  		// Argument contains shell metacharacters. Double quote the
    25  		// argument, and backslash-escape any characters that still have
    26  		// meaning inside of double quotes.
    27  		e := regexp.MustCompile("([$`\"\\\\])").ReplaceAllString(arg, `\$1`)
    28  		return fmt.Sprintf(`"%s"`, e)
    29  	}
    30  	return arg
    31  }
    32  
    33  // Escape TODO(peter): document
    34  func Escape(args []string) string {
    35  	escaped := make([]string, len(args))
    36  	for i := range args {
    37  		escaped[i] = Escape1(args[i])
    38  	}
    39  	return strings.Join(escaped, " ")
    40  }