aboutsummaryrefslogtreecommitdiff
path: root/cmd/myshell/main.go
blob: cbb3c029ffd962a8ed5af4d762ca7c6597f92937 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var KnowCommands = map[string]int{"exit": 0, "echo": 1, "type": 2}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	for {
		fmt.Fprint(os.Stdout, "$ ")

		in, err := stdin.ReadString('\n')
		if err != nil {
			fmt.Println(err.Error())
		}

		trim := strings.TrimSpace(in)

		command := strings.Split(trim, " ")

		switch command[0] {
		case "exit":
			code, err := strconv.Atoi(command[1])
			if err != nil {
				fmt.Println(err.Error())
			}
			os.Exit(code)
		case "echo":
			fmt.Println(strings.Join(command[1:], " "))
		case "type":
			switch command[1] {
			case "exit", "echo", "type":
				fmt.Printf("%s is a shell builtin\n", command[1])
			default:
				env := os.Getenv("PATH")
				paths := strings.Split(env, ":")

				for _, path := range paths {
					exec := path + "/" + command[1]

					if _, err := os.Stat(exec); err == nil {
						fmt.Printf("%s is %s\n", command[1], exec)
						break
					}
				}
				fmt.Printf("%s not found\n", command[1])
			}
		default:
			fmt.Printf("%s: command not found\n", command[0])
		}
	}
}