PreRun and PostRun Hooks

It is possible to run functions before or after the main Run function of your command. The PersistentPreRun and PreRun functions will be executed before Run. PersistentPostRun and PostRun will be executed after Run. The Persistent*Run functions will be inherited by children if they do not declare their own. These functions are run in the following order:

  • PersistentPreRun
  • PreRun
  • Run
  • PostRun
  • PersistentPostRun

An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command’s PersistentPreRun but not the root command’s PersistentPostRun:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/spf13/cobra"
  5. )
  6. func main() {
  7. var rootCmd = &cobra.Command{
  8. Use: "root [sub]",
  9. Short: "My root command",
  10. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  11. fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
  12. },
  13. PreRun: func(cmd *cobra.Command, args []string) {
  14. fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
  15. },
  16. Run: func(cmd *cobra.Command, args []string) {
  17. fmt.Printf("Inside rootCmd Run with args: %v\n", args)
  18. },
  19. PostRun: func(cmd *cobra.Command, args []string) {
  20. fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
  21. },
  22. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  23. fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
  24. },
  25. }
  26. var subCmd = &cobra.Command{
  27. Use: "sub [no options!]",
  28. Short: "My subcommand",
  29. PreRun: func(cmd *cobra.Command, args []string) {
  30. fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
  31. },
  32. Run: func(cmd *cobra.Command, args []string) {
  33. fmt.Printf("Inside subCmd Run with args: %v\n", args)
  34. },
  35. PostRun: func(cmd *cobra.Command, args []string) {
  36. fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
  37. },
  38. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  39. fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
  40. },
  41. }
  42. rootCmd.AddCommand(subCmd)
  43. rootCmd.SetArgs([]string{""})
  44. rootCmd.Execute()
  45. fmt.Println()
  46. rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
  47. rootCmd.Execute()
  48. }

Output:

  1. Inside rootCmd PersistentPreRun with args: []
  2. Inside rootCmd PreRun with args: []
  3. Inside rootCmd Run with args: []
  4. Inside rootCmd PostRun with args: []
  5. Inside rootCmd PersistentPostRun with args: []
  6. Inside rootCmd PersistentPreRun with args: [arg1 arg2]
  7. Inside subCmd PreRun with args: [arg1 arg2]
  8. Inside subCmd Run with args: [arg1 arg2]
  9. Inside subCmd PostRun with args: [arg1 arg2]
  10. Inside subCmd PersistentPostRun with args: [arg1 arg2]