Created
November 7, 2018 08:25
-
-
Save bxcodec/da11f6e398981cbf49ceb265859f7997 to your computer and use it in GitHub Desktop.
Simple Shell Application in Go
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 characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"os/exec" | |
"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) | |
// 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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment