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.
Simple Shell With Custom
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 "plus":
// not using `sum` because it's a default command in unix.
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment