aboutsummaryrefslogtreecommitdiff
path: root/toys/posix/pwd.c
blob: c7dc78f7b97b41e951d6f7c6df69ced8b279550c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* pwd.c - Print working directory.
 *
 * Copyright 2006 Rob Landley <rob@landley.net>
 *
 * See http://opengroup.org/onlinepubs/9699919799/utilities/pwd.html

USE_PWD(NEWTOY(pwd, ">0LP[-LP]", TOYFLAG_BIN|TOYFLAG_MAYFORK))

config PWD
  bool "pwd"
  default y
  help
    usage: pwd [-L|-P]

    Print working (current) directory.

    -L	Use shell's path from $PWD (when applicable)
    -P	Print canonical absolute path
*/

#define FOR_pwd
#include "toys.h"

void pwd_main(void)
{
  char *s, *pwd = getcwd(0, 0), *PWD;

  // Only use $PWD if it's an absolute path alias for cwd with no "." or ".."
  if (!FLAG(P) && (s = PWD = getenv("PWD"))) {
    struct stat st1, st2;

    while (*s == '/') {
      if (*(++s) == '.') {
        if (s[1] == '/' || !s[1]) break;
        if (s[1] == '.' && (s[2] == '/' || !s[2])) break;
      }
      while (*s && *s != '/') s++;
    }
    if (!*s && s != PWD) s = PWD;
    else s = 0;

    // If current directory exists, make sure it matches.
    if (s && pwd)
        if (stat(pwd, &st1) || stat(PWD, &st2) || st1.st_ino != st2.st_ino ||
            st1.st_dev != st2.st_dev) s = 0;
  } else s = 0;

  // If -L didn't give us a valid path, use cwd.
  if (s || (s = pwd)) puts(s);
  free(pwd);
  if (!s) perror_exit("xgetcwd");
}