Skip to content

Instantly share code, notes, and snippets.

@lomomike
Created February 5, 2018 08:03
Show Gist options
  • Save lomomike/ad8f747faafe4164ef1b0517ca10d126 to your computer and use it in GitHub Desktop.
Save lomomike/ad8f747faafe4164ef1b0517ca10d126 to your computer and use it in GitHub Desktop.
go shell
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strings"
)
type Command struct {
Command string
Agruments []string
Wait bool
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
input := true
for input {
fmt.Print("osh> ")
input = scanner.Scan()
if !input {
break
}
text := scanner.Text()
command := parse(text)
run(command)
//fmt.Printf("Command \"%s\", args \"%s\", wait : %t\n", command.Command, strings.Join(command.Agruments, " "), command.Wait)
}
}
func parse(input string) Command {
inputParts := strings.Split(strings.Trim(input, " "), " ")
wait := inputParts[len(inputParts)-1] != "&"
args := make([]string, len(inputParts)-1)
lastIndex := len(inputParts)
if !wait {
lastIndex--
}
copy(args, inputParts[1:lastIndex])
command := Command{Command: inputParts[0], Agruments: args, Wait: wait}
return command
}
func run(command Command) {
cmd := exec.Command(command.Command, command.Agruments...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
if command.Wait {
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment