Skip to content

Instantly share code, notes, and snippets.

@bxcodec
Created November 7, 2018 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxcodec/da11f6e398981cbf49ceb265859f7997 to your computer and use it in GitHub Desktop.
Save bxcodec/da11f6e398981cbf49ceb265859f7997 to your computer and use it in GitHub Desktop.
Simple Shell Application in Go
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