6 Cwd - get pathname of current working directory
14 my $abs_path = abs_path($file);
18 This module provides functions for determining the pathname of the
19 current working directory. It is recommended that getcwd (or another
20 *cwd() function) be used in I<all> code to ensure portability.
22 By default, it exports the functions cwd(), getcwd(), fastcwd(), and
23 fastgetcwd() into the caller's namespace.
26 =head2 getcwd and friends
28 Each of these functions are called without arguments and return the
29 absolute path of the current working directory.
37 Returns the current working directory.
39 Re-implements the getcwd(3) (or getwd(3)) functions in Perl.
47 The cwd() is the most natural form for the current architecture. For
48 most systems it is identical to `pwd` (but without the trailing line
57 A more dangerous version of getcwd(), but potentially faster.
59 It might conceivably chdir() you out of a directory that it can't
60 chdir() you back into. If fastcwd encounters a problem it will return
61 undef but will probably leave you in a different directory. For a
62 measure of extra security, if everything appears to have worked, the
63 fastcwd() function will check that it leaves you in the same directory
64 that it started in. If it has changed it will C<die> with the message
65 "Unstable directory path, current directory changed
66 unexpectedly". That should never happen.
70 my $cwd = fastgetcwd();
72 The fastgetcwd() function is provided as a synonym for cwd().
77 =head2 abs_path and friends
79 These functions are exported only on request. They each take a single
80 argument and return the absolute pathname for it.
86 my $abs_path = abs_path($file);
88 Uses the same algorithm as getcwd(). Symbolic links and relative-path
89 components ("." and "..") are resolved to return the canonical
90 pathname, just like realpath(3).
96 my $abs_path = realpath($file);
98 A synonym for abs_path().
104 my $abs_path = fast_abs_path($file);
106 A more dangerous, but potentially faster version of abs_path.
108 This function is B<Not> taint-safe : you can't use it in programs
109 that work under taint mode.
115 If you ask to override your chdir() built-in function,
119 then your PWD environment variable will be kept up to date. Note that
120 it will only be kept up to date if all packages which use chdir import
130 Since the path seperators are different on some operating systems ('/'
131 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
132 modules wherever portability is a concern.
136 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
137 functions are all aliases for the C<cwd()> function, which, on Mac OS,
138 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
153 our $VERSION = '2.06';
155 use base qw/ Exporter /;
156 our @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
157 our @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
159 # sys_cwd may keep the builtin command
161 # All the functionality of this module may provided by builtins,
162 # there is no sense to process the rest of the file.
163 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
165 if ($^O eq 'os2' && defined &sys_cwd && defined &sys_abspath) {
171 *abs_path = \&sys_abspath;
172 *fast_abs_path = \&abs_path;
173 *realpath = \&abs_path;
174 *fast_realpath = \&abs_path;
180 undef *Cwd::fastcwd; # avoid redefinition warning
181 XSLoader::load('Cwd');
185 # Find the pwd command in the expected locations. We assume these
186 # are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
187 # so everything works under taint mode.
189 foreach my $try (qw(/bin/pwd /usr/bin/pwd)) {
196 if (-x '/QOpenSys/bin/pwd') { # OS/400 PASE.
197 $pwd_cmd = '/QOpenSys/bin/pwd' ;
199 # Isn't this wrong? _backtick_pwd() will fail if somenone has
200 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
201 # See [perl #16774]. --jhi
206 # The 'natural and safe form' for UNIX (pwd may be setuid root)
208 local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};
209 my $cwd = `$pwd_cmd`;
210 # Belt-and-suspenders in case someone said "undef $/".
212 # `pwd` may fail e.g. if the disk is full
213 chomp($cwd) if defined $cwd;
217 # Since some ports may predefine cwd internally (e.g., NT)
218 # we take care not to override an existing definition for cwd().
220 unless(defined &cwd) {
221 # The pwd command is not available in some chroot(2)'ed environments
222 if( $^O eq 'MacOS' || (defined $ENV{PATH} &&
223 grep { -x "$_/pwd" } split(':', $ENV{PATH})) )
225 *cwd = \&_backtick_pwd;
232 # set a reasonable (and very safe) default for fastgetcwd, in case it
233 # isn't redefined later (20001212 rspier)
236 # By Brandon S. Allbery
238 # Usage: $cwd = getcwd();
248 # Usage: $cwd = &fastcwd;
250 # This is a faster version of getcwd. It's also more dangerous because
251 # you might chdir out of a directory that you can't chdir back into.
254 my($odev, $oino, $cdev, $cino, $tdev, $tino);
258 my($orig_cdev, $orig_cino) = stat('.');
259 ($cdev, $cino) = ($orig_cdev, $orig_cino);
262 ($odev, $oino) = ($cdev, $cino);
263 CORE::chdir('..') || return undef;
264 ($cdev, $cino) = stat('.');
265 last if $odev == $cdev && $oino == $cino;
266 opendir(DIR, '.') || return undef;
268 $direntry = readdir(DIR);
269 last unless defined $direntry;
270 next if $direntry eq '.';
271 next if $direntry eq '..';
273 ($tdev, $tino) = lstat($direntry);
274 last unless $tdev != $odev || $tino != $oino;
277 return undef unless defined $direntry; # should never happen
278 unshift(@path, $direntry);
280 $path = '/' . join('/', @path);
281 if ($^O eq 'apollo') { $path = "/".$path; }
282 # At this point $path may be tainted (if tainting) and chdir would fail.
283 # Untaint it then check that we landed where we started.
284 $path =~ /^(.*)\z/s # untaint
285 && CORE::chdir($1) or return undef;
286 ($cdev, $cino) = stat('.');
287 die "Unstable directory path, current directory changed unexpectedly"
288 if $cdev != $orig_cdev || $cino != $orig_cino;
293 # Keeps track of current working directory in PWD environment var
301 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
302 my($dd,$di) = stat('.');
303 my($pd,$pi) = stat($ENV{'PWD'});
304 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
310 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
313 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
314 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
315 my($pd,$pi) = stat($2);
316 my($dd,$di) = stat($1);
317 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
325 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
326 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
327 chdir_init() unless $chdir_init;
329 if ($^O eq 'MSWin32') {
330 # get the full path name *before* the chdir()
331 $newpwd = Win32::GetFullPathName($newdir);
334 return 0 unless CORE::chdir $newdir;
337 return $ENV{'PWD'} = $ENV{'DEFAULT'}
339 elsif ($^O eq 'MacOS') {
340 return $ENV{'PWD'} = cwd();
342 elsif ($^O eq 'MSWin32') {
343 $ENV{'PWD'} = $newpwd;
347 if ($newdir =~ m#^/#s) {
348 $ENV{'PWD'} = $newdir;
350 my @curdir = split(m#/#,$ENV{'PWD'});
351 @curdir = ('') unless @curdir;
353 foreach $component (split(m#/#, $newdir)) {
354 next if $component eq '.';
355 pop(@curdir),next if $component eq '..';
356 push(@curdir,$component);
358 $ENV{'PWD'} = join('/',@curdir) || '/';
364 # In case the XS version doesn't load.
365 *abs_path = \&_perl_abs_path unless defined &abs_path;
368 my $start = @_ ? shift : '.';
369 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
371 unless (@cst = stat( $start ))
373 carp "stat($start): $!";
383 unless (opendir(PARENT, $dotdots))
385 carp "opendir($dotdots): $!";
388 unless (@cst = stat($dotdots))
390 carp "stat($dotdots): $!";
394 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
402 unless (defined ($dir = readdir(PARENT)))
404 carp "readdir($dotdots): $!";
408 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
410 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
413 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
415 } while (defined $dir);
416 chop($cwd) unless $cwd eq '/'; # drop the trailing /
421 # added function alias for those of us more
422 # used to the libc function. --tchrist 27-Jan-00
423 *realpath = \&abs_path;
428 my $path = @_ ? shift : File::Spec->curdir;
429 CORE::chdir($path) || croak "Cannot chdir to $path: $!";
430 my $realpath = getcwd();
431 -d $cwd && CORE::chdir($cwd) ||
432 croak "Cannot chdir back to $cwd: $!";
436 # added function alias to follow principle of least surprise
437 # based on previous aliasing. --tchrist 27-Jan-00
438 *fast_realpath = \&fast_abs_path;
441 # --- PORTING SECTION ---
443 # VMS: $ENV{'DEFAULT'} points to default directory at all times
444 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
445 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
446 # in the process logical name table as the default device and directory
447 # seen by Perl. This may not be the same as the default device
448 # and directory seen by DCL after Perl exits, since the effects
449 # the CRTL chdir() function persist only until Perl exits.
452 return $ENV{'DEFAULT'};
456 return $ENV{'DEFAULT'} unless @_;
457 my $path = VMS::Filespec::pathify($_[0]);
458 croak("Invalid path name $_[0]") unless defined $path;
459 return VMS::Filespec::rmsexpand($path);
463 $ENV{'PWD'} = `cmd /c cd`;
465 $ENV{'PWD'} =~ s:\\:/:g ;
470 $ENV{'PWD'} = Win32::GetCwd();
471 $ENV{'PWD'} =~ s:\\:/:g ;
475 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
476 defined &Win32::GetCwd);
478 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
481 if (!defined &Dos::GetCwd) {
482 $ENV{'PWD'} = `command /c cd`;
484 $ENV{'PWD'} =~ s:\\:/:g ;
486 $ENV{'PWD'} = Dos::GetCwd();
492 local $ENV{PATH} = '';
493 local $ENV{CDPATH} = '';
494 local $ENV{ENV} = '';
495 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
501 local $ENV{PATH} = '';
502 local $ENV{CDPATH} = '';
503 local $ENV{ENV} = '';
504 my $path = @_ ? shift : '.';
505 my $realpath=`/usr/bin/fullpath -t $path`;
511 $ENV{'PWD'} = EPOC::getcwd();
516 no warnings; # assignments trigger 'subroutine redefined' warning
520 *getcwd = \&_vms_cwd;
521 *fastcwd = \&_vms_cwd;
522 *fastgetcwd = \&_vms_cwd;
523 *abs_path = \&_vms_abs_path;
524 *fast_abs_path = \&_vms_abs_path;
526 elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
527 # We assume that &_NT_cwd is defined as an XSUB or in the core.
530 *fastcwd = \&_NT_cwd;
531 *fastgetcwd = \&_NT_cwd;
532 *abs_path = \&fast_abs_path;
533 *realpath = \&fast_abs_path;
535 elsif ($^O eq 'os2') {
536 # sys_cwd may keep the builtin command
537 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
541 *abs_path = \&fast_abs_path;
543 elsif ($^O eq 'dos') {
545 *getcwd = \&_dos_cwd;
546 *fastgetcwd = \&_dos_cwd;
547 *fastcwd = \&_dos_cwd;
548 *abs_path = \&fast_abs_path;
550 elsif ($^O =~ m/^(?:qnx|nto)$/ ) {
552 *getcwd = \&_qnx_cwd;
553 *fastgetcwd = \&_qnx_cwd;
554 *fastcwd = \&_qnx_cwd;
555 *abs_path = \&_qnx_abs_path;
556 *fast_abs_path = \&_qnx_abs_path;
558 elsif ($^O eq 'cygwin') {
562 *abs_path = \&fast_abs_path;
564 elsif ($^O eq 'epoc') {
566 *getcwd = \&_epoc_cwd;
567 *fastgetcwd = \&_epoc_cwd;
568 *fastcwd = \&_epoc_cwd;
569 *abs_path = \&fast_abs_path;
571 elsif ($^O eq 'MacOS') {
575 *abs_path = \&fast_abs_path;