Last active
August 7, 2020 16:32
-
-
Save bxcodec/19c22a4e33ac4c9cb116e204e2a94f99 to your computer and use it in GitHub Desktop.
Revisions
-
bxcodec revised this gist
Nov 9, 2018 . 1 changed file with 2 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -30,7 +30,8 @@ func runCommand(commandStr string) error { switch arrCommandStr[0] { case "exit": os.Exit(0) case "plus": // not using `sum` because it's a default command in unix. if len(arrCommandStr) < 3 { return errors.New("Required for 2 arguments") } -
bxcodec created this gist
Nov 9, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ package main import ( "bufio" "errors" "fmt" "os" "os/exec" "strconv" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) for { fmt.Print("$ ") cmdString, err := reader.ReadString('\n') if err != nil { fmt.Fprintln(os.Stderr, err) } err = runCommand(cmdString) if err != nil { fmt.Fprintln(os.Stderr, err) } } } func runCommand(commandStr string) error { commandStr = strings.TrimSuffix(commandStr, "\n") arrCommandStr := strings.Fields(commandStr) switch arrCommandStr[0] { case "exit": os.Exit(0) case "sum": if len(arrCommandStr) < 3 { return errors.New("Required for 2 arguments") } arrNum := []int64{} for i, arg := range arrCommandStr { if i == 0 { continue } n, _ := strconv.ParseInt(arg, 10, 64) arrNum = append(arrNum, n) } fmt.Fprintln(os.Stdout, sum(arrNum...)) return nil // add another case here for custom commands. } cmd := exec.Command(arrCommandStr[0], arrCommandStr[1:]...) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd.Run() } func sum(numbers ...int64) int64 { res := int64(0) for _, num := range numbers { res += num } return res }