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 7USE_PWD(NEWTOY(pwd, ">0LP[-LP]", TOYFLAG_BIN|TOYFLAG_MAYFORK)) 8 9config PWD 10 bool "pwd" 11 default y 12 help 13 usage: pwd [-L|-P] 14 15 Print working (current) directory. 16 17 -L Use shell's path from $PWD (when applicable) 18 -P Print canonical absolute path 19*/ 20 21#define FOR_pwd 22#include "toys.h" 23 24void pwd_main(void) 25{ 26 char *s, *pwd = getcwd(0, 0), *PWD; 27 28 // Only use $PWD if it's an absolute path alias for cwd with no "." or ".." 29 if (!FLAG(P) && (s = PWD = getenv("PWD"))) { 30 struct stat st1, st2; 31 32 while (*s == '/') { 33 if (*(++s) == '.') { 34 if (s[1] == '/' || !s[1]) break; 35 if (s[1] == '.' && (s[2] == '/' || !s[2])) break; 36 } 37 while (*s && *s != '/') s++; 38 } 39 if (!*s && s != PWD) s = PWD; 40 else s = 0; 41 42 // If current directory exists, make sure it matches. 43 if (s && pwd) 44 if (stat(pwd, &st1) || stat(PWD, &st2) || st1.st_ino != st2.st_ino || 45 st1.st_dev != st2.st_dev) s = 0; 46 } else s = 0; 47 48 // If -L didn't give us a valid path, use cwd. 49 if (s || (s = pwd)) puts(s); 50 free(pwd); 51 if (!s) perror_exit("xgetcwd"); 52} 53