A Go library for executing and managing command-line operations with robust error handling and output management.
The cmdx
library simplifies command execution in Go applications.
It provides functions to run commands, capture output, and manage errors effectively with structured error types CommandError
.
Additionally, cmdx
includes a configurable Config
struct, which allows users to customize execution settings,
such as enabling command output printing and specifying the default directory for command execution.
To install the library, run the following command:
go get -u github.com/kgs19/cmdx
Use RunCommandPrintOutput
to execute a command and print the output:
package main
import (
"github.com/kgs19/cmdx"
"log"
)
func main() {
if err := cmdx.RunCommandPrintOutput("ls", "-l"); err != nil {
log.Fatalf("Command failed: %v", err)
}
}
If a command fails, a CommandError
instance is returned, providing detailed information:
package main
import (
"errors"
"fmt"
"github.com/kgs19/cmdx"
"log"
)
func main() {
err := cmdx.RunCommandPrintOutput("ls", "/non_existent_file.txt")
var cmdErr *cmdx.CommandError
if errors.As(err, &cmdErr) {
fmt.Printf("Command failed with exit code %d\n", cmdErr.ExitCode)
fmt.Printf("Error message: %s\n", cmdErr.ErrorMsg)
fmt.Printf("Execution directory: %s\n", cmdErr.CmdDir)
} else if err != nil {
log.Fatalf("Unexpected error: %v", err)
}
}
View the examples directory for more examples of using the cmdx
library.
The cmdx library includes configurable settings through the Config
struct, allowing you to customize command execution:
PrintCommandEnabled
: Set to true to enable printing each command before execution. This can be also controlled by the environment variableCMDX_PRINT_COMMAND_ENABLED
.CommandDir
:Specify the directory for executing the commands. This can be also controlled by the environment variableCMDX_COMMAND_DIR
.
Examples of updating configuration:
1. example custom config
2. example env variable
Contributions are welcome! Feel free to submit issues or create pull requests.