Can shell scripts be written by golang?
Today, I will talk to you about whether shell scripts can be written by golang. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Can golang write shell scripts?
Golang can write shell scripts, first of all, you can create a reader to access the keyboard, every time you press the enter key, any writes will be stored in the input variable; then according to the incoming and outgoing data to perform logical operations; finally, the processing results will be used "fmt.Println ()" to output the data.
Code example:
Package mainimport ("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's output. Err: = cmd.Run () if err! = nil {return err} return nil} after reading the above, do you have any further understanding that shell scripts can be written by golang? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.