| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package main
- import (
- "os"
- "strconv"
- "strings"
- )
- // 左移参数
- func cmd_shift(fields []string, stdin *os.File, stdout *os.File, stderr *os.File) {
- if len(fields) > 2 { // 最多1个参数
- panic("shift: too many arguments")
- }
- if len(fields) == 1 { // 如果没有指定左移几次
- fields = append(fields, "1") // 则默认为1
- }
- num, err := strconv.Atoi(fields[1]) // 字符串转数字
- if err != nil {
- panic("shift: " + fields[1] + ": numeric argument required")
- }
- if num < 0 {
- panic("shift: argument to shift must be non-negative")
- }
- tot, _ := strconv.Atoi(os.Getenv("#")) // 获取参数个数
- if num > tot {
- panic("shift: shift count must be <= $#")
- }
- args := []string{} // 参数数组
- for i := 1; i <= tot-num; i++ { // 设置参数
- args = append(args, os.Getenv(strconv.Itoa(i+num)))
- os.Setenv(strconv.Itoa(i), args[len(args)-1])
- }
- for i := tot - num + 1; i <= tot; i++ { // 重设参数
- os.Unsetenv(strconv.Itoa(i))
- }
- os.Setenv("#", strconv.Itoa(tot-num)) // 更新参数个数
- os.Setenv("*", strings.Join(args, " ")) // 更新所有命令行参数的值
- }
|