cmd_cd.go 644 B

123456789101112131415161718192021222324252627282930
  1. package main
  2. import (
  3. "os"
  4. )
  5. // 修改工作目录
  6. func cmd_cd(fields []string, stdin *os.File, stdout *os.File, stderr *os.File) {
  7. if len(fields) > 2 { // 最多1个参数
  8. panic("cd: too many arguments")
  9. }
  10. if len(fields) == 1 { // 如果没有指定目录,则切换到home
  11. fields = append(fields, os.Getenv("HOME"))
  12. }
  13. if fields[1] == "~" { // 如果指定目录为~,则切换到home
  14. fields[1] = os.Getenv("HOME")
  15. }
  16. err := os.Chdir(fields[1]) // 切换目录
  17. if err != nil {
  18. panic(err)
  19. }
  20. dir, err := os.Getwd() // 获取工作目录
  21. if err != nil {
  22. panic(err)
  23. }
  24. os.Setenv("PWD", dir) // 更新pwd环境变量
  25. }