cmd_set.go 780 B

123456789101112131415161718192021222324252627282930
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  6. "strings"
  7. )
  8. // 显示所有环境变量或设置命令行参数
  9. func cmd_set(fields []string, stdin *os.File, stdout *os.File, stderr *os.File) {
  10. if len(fields) == 1 { // 如果没有参数
  11. for _, env := range os.Environ() { // 则输出所有用户和shell环境变量
  12. fmt.Fprintln(stdout, env)
  13. }
  14. } else {
  15. tot, _ := strconv.Atoi(os.Getenv("#")) // 获取参数个数
  16. for i := 1; i <= tot; i++ { // 重设所有参数
  17. os.Unsetenv(strconv.Itoa(i))
  18. }
  19. for i := 1; i < len(fields); i++ { // 设置新参数
  20. os.Setenv(strconv.Itoa(i), fields[i])
  21. }
  22. os.Setenv("#", strconv.Itoa(len(fields)-1)) // 更新参数个数
  23. os.Setenv("*", strings.Join(fields[1:], " ")) // 更新所有命令行参数的值
  24. }
  25. }