github.com/grailbio/bigslice@v0.0.0-20230519005545-30c4c12152ad/exec/command.go (about)

     1  // Copyright 2020 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package exec
     6  
     7  import (
     8  	"os"
     9  	"strings"
    10  )
    11  
    12  // shellQuote quotes a string to be used as an argument in an sh command line.
    13  func shellQuote(s string) string {
    14  	// We wrap with single quotes, as they will work with any string except
    15  	// those with single quotes. We handle single quotes by transforming them
    16  	// into "'\''" and letting the shell concatenate the strings back together.
    17  	return "'" + strings.Replace(s, "'", `'\''`, -1) + "'"
    18  }
    19  
    20  // command returns the command-line of the current execution. The format can be
    21  // directly pasted into sh to be run.
    22  func command() string {
    23  	args := make([]string, len(os.Args))
    24  	for i := range args {
    25  		args[i] = shellQuote(os.Args[i])
    26  	}
    27  	return strings.Join(args, " ")
    28  }