hzDocs

Command: Invoke program

Invoking program

Invoking external program and Shell command

.InvokeShell(shellCmdLine) and .UseShell(shellPath) can be used for launching a Shell command (just like ls -la), the last one could specify which concrete shell (bash, or zsh?) will be used, or by using a default one.

.InvokeProc(program) can be used for launching a external executable file.

As in macOS, .InvokeProc("say 'hello world'") would execute say command and play voice with hello world text.

A program means it should not be a shell command. If you're really needing that, trying with bash -c echo "hello".

We commonly launch a GUI app with it.

Difinitions

The examples/demo/ showes howto using invokeXXX, in cmd/invoke.go:

package main
 
import (
	"context"
	"os"
 
	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/cmdr/v2/examples/cmd"
	logz "github.com/hedzr/logg/slog"
)
 
const (
	appName = "demo-app"
	desc    = ``
	version = cmdr.Version
	author  = ``
)
 
func main() {
	app := cmdr.Create(appName, version, author, desc).
    With(func(app cli.App) {
	  }).
    WithAdders(cmd.Commands...).
    Build()
 
	ctx := context.Background()
	if err := app.Run(ctx); err != nil {
		logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build
		os.Exit(app.SuggestRetCode())
	} else if rc := app.SuggestRetCode(); rc != 0 {
		os.Exit(rc)
	}
}

Run

The result with the example app is,

$ go run ./examples/demo invoke shell
... ls results ...
$ go run ./examples/demo invoke proc
(play voice with say)
$

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page