>  기사  >  golang이 쉘 스크립트를 작성할 수 있나요?

golang이 쉘 스크립트를 작성할 수 있나요?

Guanhui
Guanhui원래의
2020-05-12 13:45:573190검색

golang이 쉘 스크립트를 작성할 수 있나요?

golang은 쉘 스크립트를 작성할 수 있습니까?

golang은 쉘 스크립트를 작성할 수 있습니다. 먼저 Enter 키를 누를 때마다 키보드에 액세스할 수 있습니다. ; 그런 다음 들어오고 나가는 데이터를 기반으로 논리 연산을 수행하고 마지막으로 "fmt.Println()"을 사용하여 처리 결과를 출력합니다.

코드 예:

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}

추천 튜토리얼: "Go Tutorial"

위 내용은 golang이 쉘 스크립트를 작성할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.