diff --git a/command_run.go b/command_run.go index 855eb97324..578683da4a 100644 --- a/command_run.go +++ b/command_run.go @@ -207,9 +207,14 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context } for _, flag := range cmd.allFlags() { + isSet := flag.IsSet() if err := flag.PostParse(); err != nil { return ctx, err } + // add env set flags here + if !isSet && flag.IsSet() { + cmd.setFlags[flag] = struct{}{} + } } if cmd.After != nil && !cmd.Root().shellCompletion { diff --git a/flag_test.go b/flag_test.go index a509987211..4fd1890205 100644 --- a/flag_test.go +++ b/flag_test.go @@ -1727,6 +1727,28 @@ func TestParseGenericFromEnv(t *testing.T) { assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"})) } +func TestFlagActionFromEnv(t *testing.T) { + t.Setenv("X", "42") + x := 0 + + cmd := &Command{ + Flags: []Flag{ + &IntFlag{ + Name: "x", + Sources: EnvVars("X"), + Action: func(ctx context.Context, cmd *Command, v int) error { + x = v + return nil + }, + }, + }, + } + + assert.NoError(t, cmd.Run(buildTestContext(t), []string{"run"})) + assert.Equal(t, cmd.Int("x"), 42) + assert.Equal(t, x, 42) +} + func TestParseMultiString(t *testing.T) { _ = (&Command{ Flags: []Flag{