title: Parse strings like command line arguments with Go
body: <p>How do I take a string and parse it as if it was a series of command line arguments? I want to be able to take a string and parse that with flag and/or pflag. How do I do this?</p>
  <pre><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;os&quot;
  
      flag &quot;github.com/spf13/pflag&quot;
  )
  
  func main() {
      command := `unimportant -fb &quot;quoted string&quot;`
      var (
          foo bool
          bar string
      )
      flag.BoolVarP(&amp;foo, &quot;foo&quot;, &quot;f&quot;, false, &quot;foo&quot;)
      flag.StringVarP(&amp;bar, &quot;bar&quot;, &quot;b&quot;, &quot;default&quot;, &quot;bar&quot;)
  
      // Parse command
      os.Args = append(os.Args, &quot;-fb&quot;, &quot;quoted string&quot;)
      flag.Parse()
  
      fmt.Println(command)
      fmt.Println(&quot;foo&quot;, foo)
      fmt.Println(&quot;bar&quot;, bar)
  }
  </code></pre>