cmd_shift.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "os"
  4. "strconv"
  5. "strings"
  6. )
  7. // 左移参数
  8. func cmd_shift(fields []string, stdin *os.File, stdout *os.File, stderr *os.File) {
  9. if len(fields) > 2 { // 最多1个参数
  10. panic("shift: too many arguments")
  11. }
  12. if len(fields) == 1 { // 如果没有指定左移几次
  13. fields = append(fields, "1") // 则默认为1
  14. }
  15. num, err := strconv.Atoi(fields[1]) // 字符串转数字
  16. if err != nil {
  17. panic("shift: " + fields[1] + ": numeric argument required")
  18. }
  19. if num < 0 {
  20. panic("shift: argument to shift must be non-negative")
  21. }
  22. tot, _ := strconv.Atoi(os.Getenv("#")) // 获取参数个数
  23. if num > tot {
  24. panic("shift: shift count must be <= $#")
  25. }
  26. args := []string{} // 参数数组
  27. for i := 1; i <= tot-num; i++ { // 设置参数
  28. args = append(args, os.Getenv(strconv.Itoa(i+num)))
  29. os.Setenv(strconv.Itoa(i), args[len(args)-1])
  30. }
  31. for i := tot - num + 1; i <= tot; i++ { // 重设参数
  32. os.Unsetenv(strconv.Itoa(i))
  33. }
  34. os.Setenv("#", strconv.Itoa(tot-num)) // 更新参数个数
  35. os.Setenv("*", strings.Join(args, " ")) // 更新所有命令行参数的值
  36. }