DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

abdfn
abdfn

Posted on

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)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.