Home > OS >  Golang character escape in exec.Command
Golang character escape in exec.Command

Time:06-18

Hello I have a command line wrapper for exec.Command function as below :

func GenCmd(cmdline string) *exec.Cmd {
    fmt.Println("command is ", cmdline)
    // splitting head => g   parts => rest of the command
    parts := strings.Fields(cmdline)

    head := parts[0]
    parts = parts[1:len(parts)]

    // exec cmd & collect output
    cmd := exec.Command(head, parts...)
    fmt.Printf("Generated comdline : %s", cmd)
    return cmd
}

func exeCmd(cmdline string, wg *sync.WaitGroup) {
    cmd := GenCmd(cmdline)
    out, err := cmd.Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Printf("%s", out)
    wg.Done() // signal to waitgroup this goroutine complete
}

I want to call a curl command as below in my wrapper , origin curl command as below:

curl -G https://api.github.com/search/repositories       \
    --data-urlencode "q=created:>`date -v-7d ' %Y-%m-%d'`" \
    --data-urlencode "sort=stars"                          \
    --data-urlencode "order=desc"                          \
    -H "Accept: application/vnd.github.preview"            \
    | jq ".items[0,1,2] | {name, description, language, watchers_count, html_url}"

But seems like character - ` both need to be escaped at command

`date -v-7d ' %Y-%m-%d'`

Any idead how can I do that ?

main function below:

func main() {
    x := []string{
        `curl -G https://api.github.com/search/repositories `  
            `--data-urlencode "q=created:>\`date -v-7d ' %Y-%m-%d'\`" --data-urlencode 'sort=stars' --data-urlencode 'order=asc'`  
            `-H 'Accept: application/vnd.github.preview'`  
            `| jq ".items[0,1,2] | {name, description, language, watchers_count, html_url}"`
    }

    cmdCnt := len(x)
    wg := new(sync.WaitGroup)
    wg.Add(cmdCnt)

    for _, cmd := range x {
        go exeCmd(cmd, wg) // empty string output to stdout
    }

    wg.Wait()
}

Here is full golang code

CodePudding user response:

You cannot escape backticks inside backticks but you can build long string like this:

`first 
 part `   "`second part`"   `…`
  •  Tags:  
  • go
  • Related