Home  >  Article  >  Can golang write shell scripts?

Can golang write shell scripts?

Guanhui
GuanhuiOriginal
2020-05-12 13:45:573190browse

Can golang write shell scripts?

Can golang write shell scripts?

Golang can write shell scripts. First, you can create a reader to access the keyboard. Whenever When the Enter key is pressed, any write will be stored in the input variable; then logical operations are performed based on the incoming and outgoing data; and finally the processing results are output using "fmt.Println()".

Code example:

package main

import (    "bufio"
    "errors"
    "fmt"
    "os"
    "os/exec"
    "strings")

func main() {
    reader := bufio.NewReader(os.Stdin) for {
        fmt.Print("> ")     // Read the keyboad input.
        input, err := reader.ReadString('\n')       if err != nil {
            fmt.Fprintln(os.Stderr, err)
        }       // Handle the execution of the input.
        err = execInput(input)      if err != nil {
            fmt.Fprintln(os.Stderr, err)
        }
    }
}
// ErrNoPath is returned when 'cd' was called without a second argument.var ErrNoPath = errors.New("path required")

func execInput(input string) error {    // Remove the newline character.
    input = strings.TrimSuffix(input, "\n") // Split the input separate the command and the arguments.
    args := strings.Split(input, " ")   // Check for built-in commands.
    switch args[0] {    case "cd":      // 'cd' to home with empty path not yet supported.
        if len(args) < 2 {          return ErrNoPath
        }
        err := os.Chdir(args[1])        if err != nil {         return err
        }       // Stop further processing.
        return nil
    case "exit":
        os.Exit(0)
    }   // Prepare the command to execute.
    cmd := exec.Command(args[0], args[1:]...)   // Set the correct output device.
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout

    // Execute the command and save it&#39;s output.
    err := cmd.Run()    if err != nil {     return err
   }   return nil}

Recommended tutorial: "Go Tutorial"

The above is the detailed content of Can golang write shell scripts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn