pwd.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* pwd.c - Print working directory.
  2. *
  3. * Copyright 2006 Rob Landley <rob@landley.net>
  4. *
  5. * See http://opengroup.org/onlinepubs/9699919799/utilities/pwd.html
  6. USE_PWD(NEWTOY(pwd, ">0LP[-LP]", TOYFLAG_BIN|TOYFLAG_MAYFORK))
  7. config PWD
  8. bool "pwd"
  9. default y
  10. help
  11. usage: pwd [-L|-P]
  12. Print working (current) directory.
  13. -L Use shell's path from $PWD (when applicable)
  14. -P Print canonical absolute path
  15. */
  16. #define FOR_pwd
  17. #include "toys.h"
  18. void pwd_main(void)
  19. {
  20. char *s, *pwd = getcwd(0, 0), *PWD;
  21. // Only use $PWD if it's an absolute path alias for cwd with no "." or ".."
  22. if (!FLAG(P) && (s = PWD = getenv("PWD"))) {
  23. struct stat st1, st2;
  24. while (*s == '/') {
  25. if (*(++s) == '.') {
  26. if (s[1] == '/' || !s[1]) break;
  27. if (s[1] == '.' && (s[2] == '/' || !s[2])) break;
  28. }
  29. while (*s && *s != '/') s++;
  30. }
  31. if (!*s && s != PWD) s = PWD;
  32. else s = 0;
  33. // If current directory exists, make sure it matches.
  34. if (s && pwd)
  35. if (stat(pwd, &st1) || stat(PWD, &st2) || st1.st_ino != st2.st_ino ||
  36. st1.st_dev != st2.st_dev) s = 0;
  37. } else s = 0;
  38. // If -L didn't give us a valid path, use cwd.
  39. if (s || (s = pwd)) puts(s);
  40. free(pwd);
  41. if (!s) perror_exit("xgetcwd");
  42. }