Skip to content

Instantly share code, notes, and snippets.

@bxcodec
Last active August 7, 2020 16:32
Show Gist options
  • Save bxcodec/19c22a4e33ac4c9cb116e204e2a94f99 to your computer and use it in GitHub Desktop.
Save bxcodec/19c22a4e33ac4c9cb116e204e2a94f99 to your computer and use it in GitHub Desktop.

Revisions

  1. bxcodec revised this gist Nov 9, 2018. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion simple_shell.go
    Original 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 "sum":
    case "plus":
    // not using `sum` because it's a default command in unix.
    if len(arrCommandStr) < 3 {
    return errors.New("Required for 2 arguments")
    }
  2. bxcodec created this gist Nov 9, 2018.
    61 changes: 61 additions & 0 deletions simple_shell.go
    Original 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
    }