linux – Execute any command in bash-ThrowExceptions

Exception or error:

I want a Go program to run a command (including built in commands) in the bash terminal as well as display it in the terminal itself like

trial.go output.txt hello.txt
$go run trial.go pwd
$go run trial.go cd ..

As, you can see, the golang script takes the command as input, and executes it in the same terminal and environment and also displays the output

I tried the below code but it does not work for the built-in commands

cmd := exec.Command("<the input command>")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err := cmd.Run()
    if err != nil {
        log.Fatalf("cmd.Run() failed with %s\n", err)

In simple words, the input string is going to be pasted in the terminal and is executed.

How to solve:

This works for ‘one word’ commands, maybe you can fix it to work with more words. Hope is useful.

package main

import (

func main() {
    for {
    fmt.Println("Please introduce one word command (ls for example)")
    var command string

    out, err := exec.Command(command).Output()
    if err != nil {
    fmt.Printf("Your output is: %s/n",out)

Leave a Reply

Your email address will not be published. Required fields are marked *