title: Global flags and subcommands
body: <p>I'm implementing a little CLI with multiple subcommands. I'd like to support global flags, that is flags that apply to all subcommands to avoid repeating them.</p>
  <p>For example, in the example below I'm trying to have <code>-required</code> flag that is required for all subcommands.</p>
  <pre><code>package main
  
  import (
      &quot;flag&quot;
      &quot;fmt&quot;
      &quot;log&quot;
      &quot;os&quot;
  )
  
  var (
      required = flag.String(
          &quot;required&quot;,
          &quot;&quot;,
          &quot;required for all commands&quot;,
      )
      fooCmd = flag.NewFlagSet(&quot;foo&quot;, flag.ExitOnError)
      barCmd = flag.NewFlagSet(&quot;bar&quot;, flag.ExitOnError)
  )
  
  func main() {
      flag.Parse()
  
      if *required == &quot;&quot; {
          fmt.Println(&quot;-required is required for all commands&quot;)
      }
  
      switch os.Args[1] {
      case &quot;foo&quot;:
          fooCmd.Parse(os.Args[2:])
          fmt.Println(&quot;foo&quot;)
      case &quot;bar&quot;:
          barCmd.Parse(os.Args[2:])
          fmt.Println(&quot;bar&quot;)
      default:
          log.Fatalf(&quot;[ERROR] unknown subcommand '%s', see help for more details.&quot;, os.Args[1])
      }
  }
  </code></pre>
  <p>I would expect usage to be like:</p>
  <pre><code>$ go run main.go foo -required helloworld
  </code></pre>
  <p>but if I ran that with the above code I get:</p>
  <pre><code>$ go run main.go foo -required hello
  -required is required for all commands
  flag provided but not defined: -required
  Usage of foo:
  exit status 2
  </code></pre>
  <p>It looks like <code>flag.Parse()</code> is not capturing <code>-required</code> from the CLI, and then the <code>fooCmd</code> is complaining that I've given it a flag it doesn't recognize.</p>
  <p>What's the easiest way to have subcommands with global flags in Golang?</p>