6 getcwd - get pathname of current working directory
23 use Cwd 'abs_path'; # aka realpath()
24 print abs_path($ENV{'PWD'});
26 use Cwd 'fast_abs_path';
27 print fast_abs_path($ENV{'PWD'});
31 The getcwd() function re-implements the getcwd(3) (or getwd(3)) functions
34 The abs_path() function takes a single argument and returns the
35 absolute pathname for that argument. It uses the same algorithm
36 as getcwd(). (Actually, getcwd() is abs_path(".")) Symbolic links
37 and relative-path components ("." and "..") are resolved to return
38 the canonical pathname, just like realpath(3). Also callable as
41 The fastcwd() function looks the same as getcwd(), but runs faster.
42 It's also more dangerous because it might conceivably chdir() you out
43 of a directory that it can't chdir() you back into. If fastcwd
44 encounters a problem it will return undef but will probably leave you
45 in a different directory. For a measure of extra security, if
46 everything appears to have worked, the fastcwd() function will check
47 that it leaves you in the same directory that it started in. If it has
48 changed it will C<die> with the message "Unstable directory path,
49 current directory changed unexpectedly". That should never happen.
51 The fast_abs_path() function looks the same as abs_path(), but runs faster.
52 And like fastcwd() is more dangerous.
54 The cwd() function looks the same as getcwd and fastgetcwd but is
55 implemented using the most natural and safe form for the current
56 architecture. For most systems it is identical to `pwd` (but without
57 the trailing line terminator).
59 It is recommended that cwd (or another *cwd() function) is used in
60 I<all> code to ensure portability.
62 If you ask to override your chdir() built-in function, then your PWD
63 environment variable will be kept up to date. (See
64 L<perlsub/Overriding Builtin Functions>.) Note that it will only be
65 kept up to date if all packages which use chdir import it from Cwd.
73 our $VERSION = '2.04';
75 use base qw/ Exporter /;
76 our @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
77 our @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
80 # The 'natural and safe form' for UNIX (pwd may be setuid root)
84 # `pwd` may fail e.g. if the disk is full
85 chomp($cwd) if defined $cwd;
89 # Since some ports may predefine cwd internally (e.g., NT)
90 # we take care not to override an existing definition for cwd().
92 unless(defined &cwd) {
93 # The pwd command is not available in some chroot(2)'ed environments
94 if($^O eq 'MacOS' || grep { -x "$_/pwd" } split(':', $ENV{PATH})) {
95 *cwd = \&_backtick_pwd;
102 # set a reasonable (and very safe) default for fastgetcwd, in case it
103 # isn't redefined later (20001212 rspier)
106 # By Brandon S. Allbery
108 # Usage: $cwd = getcwd();
117 # Usage: $cwd = &fastcwd;
119 # This is a faster version of getcwd. It's also more dangerous because
120 # you might chdir out of a directory that you can't chdir back into.
123 my($odev, $oino, $cdev, $cino, $tdev, $tino);
127 my($orig_cdev, $orig_cino) = stat('.');
128 ($cdev, $cino) = ($orig_cdev, $orig_cino);
131 ($odev, $oino) = ($cdev, $cino);
132 CORE::chdir('..') || return undef;
133 ($cdev, $cino) = stat('.');
134 last if $odev == $cdev && $oino == $cino;
135 opendir(DIR, '.') || return undef;
137 $direntry = readdir(DIR);
138 last unless defined $direntry;
139 next if $direntry eq '.';
140 next if $direntry eq '..';
142 ($tdev, $tino) = lstat($direntry);
143 last unless $tdev != $odev || $tino != $oino;
146 return undef unless defined $direntry; # should never happen
147 unshift(@path, $direntry);
149 $path = '/' . join('/', @path);
150 if ($^O eq 'apollo') { $path = "/".$path; }
151 # At this point $path may be tainted (if tainting) and chdir would fail.
152 # To be more useful we untaint it then check that we landed where we started.
153 $path = $1 if $path =~ /^(.*)\z/s; # untaint
154 CORE::chdir($path) || return undef;
155 ($cdev, $cino) = stat('.');
156 die "Unstable directory path, current directory changed unexpectedly"
157 if $cdev != $orig_cdev || $cino != $orig_cino;
162 # Keeps track of current working directory in PWD environment var
170 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
171 my($dd,$di) = stat('.');
172 my($pd,$pi) = stat($ENV{'PWD'});
173 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
179 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
182 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
183 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
184 my($pd,$pi) = stat($2);
185 my($dd,$di) = stat($1);
186 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
194 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
195 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
196 chdir_init() unless $chdir_init;
197 return 0 unless CORE::chdir $newdir;
199 return $ENV{'PWD'} = $ENV{'DEFAULT'}
201 elsif ($^O eq 'MacOS') {
202 return $ENV{'PWD'} = cwd();
204 elsif ($^O eq 'MSWin32') {
205 $ENV{'PWD'} = Win32::GetFullPathName($newdir);
209 if ($newdir =~ m#^/#s) {
210 $ENV{'PWD'} = $newdir;
212 my @curdir = split(m#/#,$ENV{'PWD'});
213 @curdir = ('') unless @curdir;
215 foreach $component (split(m#/#, $newdir)) {
216 next if $component eq '.';
217 pop(@curdir),next if $component eq '..';
218 push(@curdir,$component);
220 $ENV{'PWD'} = join('/',@curdir) || '/';
225 # Taken from Cwd.pm It is really getcwd with an optional
226 # parameter instead of '.'
231 my $start = @_ ? shift : '.';
232 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
234 unless (@cst = stat( $start ))
236 carp "stat($start): $!";
245 unless (opendir(PARENT, $dotdots))
247 carp "opendir($dotdots): $!";
250 unless (@cst = stat($dotdots))
252 carp "stat($dotdots): $!";
256 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
264 unless (defined ($dir = readdir(PARENT)))
266 carp "readdir($dotdots): $!";
270 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
272 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
275 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
277 } while (defined $dir);
278 chop($cwd) unless $cwd eq '/'; # drop the trailing /
282 # added function alias for those of us more
283 # used to the libc function. --tchrist 27-Jan-00
284 *realpath = \&abs_path;
288 my $path = @_ ? shift : '.';
289 CORE::chdir($path) || croak "Cannot chdir to $path:$!";
290 my $realpath = getcwd();
291 CORE::chdir($cwd) || croak "Cannot chdir back to $cwd:$!";
295 # added function alias to follow principle of least surprise
296 # based on previous aliasing. --tchrist 27-Jan-00
297 *fast_realpath = \&fast_abs_path;
300 # --- PORTING SECTION ---
302 # VMS: $ENV{'DEFAULT'} points to default directory at all times
303 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
304 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
305 # in the process logical name table as the default device and directory
306 # seen by Perl. This may not be the same as the default device
307 # and directory seen by DCL after Perl exits, since the effects
308 # the CRTL chdir() function persist only until Perl exits.
311 return $ENV{'DEFAULT'};
315 return $ENV{'DEFAULT'} unless @_;
316 my $path = VMS::Filespec::pathify($_[0]);
317 croak("Invalid path name $_[0]") unless defined $path;
318 return VMS::Filespec::rmsexpand($path);
322 $ENV{'PWD'} = `cmd /c cd`;
324 $ENV{'PWD'} =~ s:\\:/:g ;
329 $ENV{'PWD'} = Win32::GetCwd();
330 $ENV{'PWD'} =~ s:\\:/:g ;
334 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
335 defined &Win32::GetCwd);
337 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
340 if (!defined &Dos::GetCwd) {
341 $ENV{'PWD'} = `command /c cd`;
343 $ENV{'PWD'} =~ s:\\:/:g ;
345 $ENV{'PWD'} = Dos::GetCwd();
351 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
357 my $path = @_ ? shift : '.';
358 my $realpath=`/usr/bin/fullpath -t $path`;
364 $ENV{'PWD'} = EPOC::getcwd();
369 no warnings; # assignments trigger 'subroutine redefined' warning
373 *getcwd = \&_vms_cwd;
374 *fastcwd = \&_vms_cwd;
375 *fastgetcwd = \&_vms_cwd;
376 *abs_path = \&_vms_abs_path;
377 *fast_abs_path = \&_vms_abs_path;
379 elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
380 # We assume that &_NT_cwd is defined as an XSUB or in the core.
383 *fastcwd = \&_NT_cwd;
384 *fastgetcwd = \&_NT_cwd;
385 *abs_path = \&fast_abs_path;
387 elsif ($^O eq 'os2') {
388 # sys_cwd may keep the builtin command
389 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
393 *abs_path = \&fast_abs_path;
395 elsif ($^O eq 'dos') {
397 *getcwd = \&_dos_cwd;
398 *fastgetcwd = \&_dos_cwd;
399 *fastcwd = \&_dos_cwd;
400 *abs_path = \&fast_abs_path;
402 elsif ($^O eq 'qnx') {
404 *getcwd = \&_qnx_cwd;
405 *fastgetcwd = \&_qnx_cwd;
406 *fastcwd = \&_qnx_cwd;
407 *abs_path = \&_qnx_abs_path;
408 *fast_abs_path = \&_qnx_abs_path;
410 elsif ($^O eq 'cygwin') {
414 *abs_path = \&fast_abs_path;
416 elsif ($^O eq 'epoc') {
418 *getcwd = \&_epoc_cwd;
419 *fastgetcwd = \&_epoc_cwd;
420 *fastcwd = \&_epoc_cwd;
421 *abs_path = \&fast_abs_path;
423 elsif ($^O eq 'MacOS') {
427 *abs_path = \&fast_abs_path;
431 # package main; eval join('',<DATA>) || die $@; # quick test
436 BEGIN { import Cwd qw(:DEFAULT chdir); }
437 print join("\n", cwd, getcwd, fastcwd, "");
439 print join("\n", cwd, getcwd, fastcwd, "");