diff --git a/README.md b/README.md index e90a536..2f96e35 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ If you want to use the cat command * dirname [detail](./dirname/README.md) * echo [detail](./echo/README.md) * head [detail](./head/README.md) +* env * link * md5sum [detail](./md5sum/README.md) * paste [detail](./paste/README.md) @@ -62,4 +63,4 @@ If you want to use the cat command * sleep [detail](./sleep/README.md) ## progress -progress = 33 / 92 = 35% +progress = 34 / 92 = 36.7% diff --git a/coreutils/coreutils.go b/coreutils/coreutils.go index 1bca605..765c44a 100644 --- a/coreutils/coreutils.go +++ b/coreutils/coreutils.go @@ -10,6 +10,7 @@ import ( "github.com/guonaihong/coreutils/cut" "github.com/guonaihong/coreutils/dirname" "github.com/guonaihong/coreutils/echo" + "github.com/guonaihong/coreutils/env" "github.com/guonaihong/coreutils/head" "github.com/guonaihong/coreutils/link" "github.com/guonaihong/coreutils/md5sum" @@ -90,6 +91,10 @@ func main() { echo.Main(os.Args[1:]) }) + parent.SubCommand("env", "Use the env subcommand", func() { + env.Main(os.Args[1:]) + }) + parent.SubCommand("head", "Use the head subcommand", func() { head.Main(os.Args[1:]) }) diff --git a/env/env.go b/env/env.go new file mode 100644 index 0000000..11545c1 --- /dev/null +++ b/env/env.go @@ -0,0 +1,60 @@ +package env + +import ( + "fmt" + "github.com/guonaihong/flag" + "os" + "os/exec" + "strings" +) + +type Env struct { + IgnoreEnvironment bool `opt:"i, ignore-environment" usage:"start with an empty environment"` + Unset string `opt:"u, unset" usage:"remove variable from the environment"` + //Chdir string `opt:"C, chdir" usage:"change working directory to DIR"` + Null bool `opt:"0, null" usage:"end each output line with NUL, not newline"` +} + +func Main(argv []string) { + var env Env + delimiter := byte('\n') + + command := flag.NewFlagSet(argv[0], flag.ExitOnError) + command.ParseStruct(argv[1:], &env) + args := command.Args() + + if env.IgnoreEnvironment { + os.Clearenv() + } + + if env.Null { + delimiter = byte(0) + } + + for k, v := range args { + if strings.IndexByte(v, '=') > 0 { + kv := strings.SplitN(v, "=", 2) + if err := os.Setenv(kv[0], kv[1]); err != nil { + fmt.Printf("%s\n", err) + } + continue + } + + cmd := exec.Command(args[k], args[k+1:]...) + cmd.Stdout = os.Stdout + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + fmt.Printf("%s\n", err) + os.Exit(1) + } + + os.Exit(0) + } + + allArgs := os.Environ() + for _, v := range allArgs { + fmt.Fprintf(os.Stdout, "%s%c", v, delimiter) + } +}