DEV Community

abdfn
abdfn

Posted on

4 1

gosh - Run powershell and bash commands easly in go.

GitHub logo abdfnx / gosh

⌨ A golang library for executing bash & powershell commands easly.

Run powershell and bash commands easly in go.

Examples

Run one command on both shell and powershell



import "github.com/abdfnx/gosh"

// run a command
gosh.Run("git status")

// run a command with output
err, out, errout := gosh.RunOut("whoami")

if err != nil {
  log.Printf("error: %v\n", err)
  fmt.Print(errout)
}

fmt.Print(out)


Enter fullscreen mode Exit fullscreen mode

How gosh.Run("COMMAND") works ?



// `Run` executes the same command for shell and powershell
func Run(cmd string) {
    err, out, errout := ShellOutput("")

    if runtime.GOOS == "windows" {
        err, out, errout = PowershellOutput(cmd)
    } else {
        err, out, errout = ShellOutput(cmd)
    }

    if err != nil {
        log.Printf("error: %v\n", err)
        fmt.Print(errout)
    }

    fmt.Print(out)
}


Enter fullscreen mode Exit fullscreen mode

Powershell



import "github.com/abdfnx/gosh"

// run a command
gosh.PowershellCommand(`Write-Host "hello from powershell"`)

// run a script
gosh.PowershellCommand(`
  $git_username = git config user.name

  Write-Host $git_username
`)

// run a command with output
err, out, errout := gosh.PowerShelloutput(`[System.Environment]::SetEnvironmentVariable("Path", $Env:Path + ";$APP_PATH\bin", [System.EnvironmentVariableTarget]::User)`)

if err != nil {
  log.Printf("error: %v\n", err)
  fmt.Print(errout)
}

fmt.Print(out)


Enter fullscreen mode Exit fullscreen mode

Bash/Shell



import "github.com/abdfnx/gosh"

// run a command
gosh.ShellCommand(`echo "shell or bash?"`)

// run a script
gosh.ShellCommand(`
  mood="👨‍💻"

  if [ $mood != "😪" ]; then
    echo "still coding"
  fi
`)

// run a command with output
err, out, errout := gosh.Shelloutput(`curl --silent "https://api.github.com/repos/abdfnx/resto/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'`)

if err != nil {
  log.Printf("error: %v\n", err)
  fmt.Print(errout)
}

fmt.Print(out)


Enter fullscreen mode Exit fullscreen mode

thank you for your time and don't forgot to star the repo if you like it

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay