5 Cwd - get pathname of current working directory
13 my $abs_path = abs_path($file);
17 This module provides functions for determining the pathname of the
18 current working directory. It is recommended that getcwd (or another
19 *cwd() function) be used in I<all> code to ensure portability.
21 By default, it exports the functions cwd(), getcwd(), fastcwd(), and
22 fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace.
25 =head2 getcwd and friends
27 Each of these functions are called without arguments and return the
28 absolute path of the current working directory.
36 Returns the current working directory.
38 Exposes the POSIX function getcwd(3) or re-implements it if it's not
45 The cwd() is the most natural form for the current architecture. For
46 most systems it is identical to `pwd` (but without the trailing line
53 A more dangerous version of getcwd(), but potentially faster.
55 It might conceivably chdir() you out of a directory that it can't
56 chdir() you back into. If fastcwd encounters a problem it will return
57 undef but will probably leave you in a different directory. For a
58 measure of extra security, if everything appears to have worked, the
59 fastcwd() function will check that it leaves you in the same directory
60 that it started in. If it has changed it will C<die> with the message
61 "Unstable directory path, current directory changed
62 unexpectedly". That should never happen.
66 my $cwd = fastgetcwd();
68 The fastgetcwd() function is provided as a synonym for cwd().
73 my $cwd = getdcwd('C:');
75 The getdcwd() function is also provided on Win32 to get the current working
76 directory on the specified drive, since Windows maintains a separate current
77 working directory for each drive. If no drive is specified then the current
80 This function simply calls the Microsoft C library _getdcwd() function.
85 =head2 abs_path and friends
87 These functions are exported only on request. They each take a single
88 argument and return the absolute pathname for it. If no argument is
89 given they'll use the current working directory.
95 my $abs_path = abs_path($file);
97 Uses the same algorithm as getcwd(). Symbolic links and relative-path
98 components ("." and "..") are resolved to return the canonical
99 pathname, just like realpath(3).
103 my $abs_path = realpath($file);
105 A synonym for abs_path().
109 my $abs_path = fast_abs_path($file);
111 A more dangerous, but potentially faster version of abs_path.
117 If you ask to override your chdir() built-in function,
121 then your PWD environment variable will be kept up to date. Note that
122 it will only be kept up to date if all packages which use chdir import
132 Since the path seperators are different on some operating systems ('/'
133 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
134 modules wherever portability is a concern.
138 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
139 functions are all aliases for the C<cwd()> function, which, on Mac OS,
140 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
147 Originally by the perl5-porters.
149 Maintained by Ken Williams <KWILLIAMS@cpan.org>
153 Copyright (c) 2004 by the Perl 5 Porters. All rights reserved.
155 This program is free software; you can redistribute it and/or modify
156 it under the same terms as Perl itself.
158 Portions of the C code in this library are copyright (c) 1994 by the
159 Regents of the University of California. All rights reserved. The
160 license on this code is compatible with the licensing of the rest of
161 the distribution - please see the source code in F<Cwd.xs> for the
172 use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
175 my $xs_version = $VERSION;
176 $VERSION = eval $VERSION;
178 @ISA = qw/ Exporter /;
179 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
180 push @EXPORT, qw(getdcwd) if $^O eq 'MSWin32';
181 @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
183 # sys_cwd may keep the builtin command
185 # All the functionality of this module may provided by builtins,
186 # there is no sense to process the rest of the file.
187 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
192 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
197 *fast_abs_path = \&sys_abspath if defined &sys_abspath;
198 *abs_path = \&fast_abs_path;
199 *realpath = \&fast_abs_path;
200 *fast_realpath = \&fast_abs_path;
205 # Need to look up the feature settings on VMS. The preferred way is to use the
206 # VMS::Feature module, but that may not be available to dual life modules.
211 if (eval { local $SIG{__DIE__}; require VMS::Feature; }) {
212 $use_vms_feature = 1;
217 # Need to look up the UNIX report mode. This may become a dynamic mode
221 if ($use_vms_feature) {
222 $unix_rpt = VMS::Feature::current("filename_unix_report");
224 my $env_unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || '';
225 $unix_rpt = $env_unix_rpt =~ /^[ET1]/i;
230 # Need to look up the EFS character set mode. This may become a dynamic
231 # mode in the future.
234 if ($use_vms_feature) {
235 $efs = VMS::Feature::current("efs_charset");
237 my $env_efs = $ENV{'DECC$EFS_CHARSET'} || '';
238 $efs = $env_efs =~ /^[ET1]/i;
244 # If loading the XS stuff doesn't work, we can fall back to pure perl
248 XSLoader::load( __PACKAGE__, $xs_version);
251 push @ISA, 'DynaLoader';
252 __PACKAGE__->bootstrap( $xs_version );
256 # Must be after the DynaLoader stuff:
257 $VERSION = eval $VERSION;
259 # Big nasty table of function aliases
265 getcwd => '_vms_cwd',
266 fastcwd => '_vms_cwd',
267 fastgetcwd => '_vms_cwd',
268 abs_path => '_vms_abs_path',
269 fast_abs_path => '_vms_abs_path',
274 # We assume that &_NT_cwd is defined as an XSUB or in the core.
277 fastcwd => '_NT_cwd',
278 fastgetcwd => '_NT_cwd',
279 abs_path => 'fast_abs_path',
280 realpath => 'fast_abs_path',
286 getcwd => '_dos_cwd',
287 fastgetcwd => '_dos_cwd',
288 fastcwd => '_dos_cwd',
289 abs_path => 'fast_abs_path',
292 # QNX4. QNX6 has a $os of 'nto'.
296 getcwd => '_qnx_cwd',
297 fastgetcwd => '_qnx_cwd',
298 fastcwd => '_qnx_cwd',
299 abs_path => '_qnx_abs_path',
300 fast_abs_path => '_qnx_abs_path',
308 abs_path => 'fast_abs_path',
309 realpath => 'fast_abs_path',
315 getcwd => '_epoc_cwd',
316 fastgetcwd => '_epoc_cwd',
317 fastcwd => '_epoc_cwd',
318 abs_path => 'fast_abs_path',
326 abs_path => 'fast_abs_path',
330 $METHOD_MAP{NT} = $METHOD_MAP{MSWin32};
333 # Find the pwd command in the expected locations. We assume these
334 # are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
335 # so everything works under taint mode.
337 foreach my $try ('/bin/pwd',
339 '/QOpenSys/bin/pwd', # OS/400 PASE.
347 my $found_pwd_cmd = defined($pwd_cmd);
349 # Isn't this wrong? _backtick_pwd() will fail if somenone has
350 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
351 # See [perl #16774]. --jhi
356 sub _carp { require Carp; Carp::carp(@_) }
357 sub _croak { require Carp; Carp::croak(@_) }
359 # The 'natural and safe form' for UNIX (pwd may be setuid root)
361 # Localize %ENV entries in a way that won't create new hash keys
362 my @localize = grep exists $ENV{$_}, qw(PATH IFS CDPATH ENV BASH_ENV);
363 local @ENV{@localize};
365 my $cwd = `$pwd_cmd`;
366 # Belt-and-suspenders in case someone said "undef $/".
368 # `pwd` may fail e.g. if the disk is full
369 chomp($cwd) if defined $cwd;
373 # Since some ports may predefine cwd internally (e.g., NT)
374 # we take care not to override an existing definition for cwd().
376 unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) {
377 # The pwd command is not available in some chroot(2)'ed environments
378 my $sep = $Config::Config{path_sep} || ':';
379 my $os = $^O; # Protect $^O from tainting
382 # Try again to find a pwd, this time searching the whole PATH.
383 if (defined $ENV{PATH} and $os ne 'MSWin32') { # no pwd on Windows
384 my @candidates = split($sep, $ENV{PATH});
385 while (!$found_pwd_cmd and @candidates) {
386 my $candidate = shift @candidates;
387 $found_pwd_cmd = 1 if -x "$candidate/pwd";
391 # MacOS has some special magic to make `pwd` work.
392 if( $os eq 'MacOS' || $found_pwd_cmd )
394 *cwd = \&_backtick_pwd;
401 if ($^O eq 'cygwin') {
402 # We need to make sure cwd() is called with no args, because it's
403 # got an arg-less prototype and will die if args are present.
405 my $orig_cwd = \&cwd;
406 *cwd = sub { &$orig_cwd() }
410 # set a reasonable (and very safe) default for fastgetcwd, in case it
411 # isn't redefined later (20001212 rspier)
414 # A non-XS version of getcwd() - also used to bootstrap the perl build
415 # process, when miniperl is running and no XS loading happens.
423 # Usage: $cwd = &fastcwd;
425 # This is a faster version of getcwd. It's also more dangerous because
426 # you might chdir out of a directory that you can't chdir back into.
429 my($odev, $oino, $cdev, $cino, $tdev, $tino);
433 my($orig_cdev, $orig_cino) = stat('.');
434 ($cdev, $cino) = ($orig_cdev, $orig_cino);
437 ($odev, $oino) = ($cdev, $cino);
438 CORE::chdir('..') || return undef;
439 ($cdev, $cino) = stat('.');
440 last if $odev == $cdev && $oino == $cino;
441 opendir(DIR, '.') || return undef;
443 $direntry = readdir(DIR);
444 last unless defined $direntry;
445 next if $direntry eq '.';
446 next if $direntry eq '..';
448 ($tdev, $tino) = lstat($direntry);
449 last unless $tdev != $odev || $tino != $oino;
452 return undef unless defined $direntry; # should never happen
453 unshift(@path, $direntry);
455 $path = '/' . join('/', @path);
456 if ($^O eq 'apollo') { $path = "/".$path; }
457 # At this point $path may be tainted (if tainting) and chdir would fail.
458 # Untaint it then check that we landed where we started.
459 $path =~ /^(.*)\z/s # untaint
460 && CORE::chdir($1) or return undef;
461 ($cdev, $cino) = stat('.');
462 die "Unstable directory path, current directory changed unexpectedly"
463 if $cdev != $orig_cdev || $cino != $orig_cino;
466 if (not defined &fastcwd) { *fastcwd = \&fastcwd_ }
469 # Keeps track of current working directory in PWD environment var
477 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
478 my($dd,$di) = stat('.');
479 my($pd,$pi) = stat($ENV{'PWD'});
480 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
486 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
489 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
490 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
491 my($pd,$pi) = stat($2);
492 my($dd,$di) = stat($1);
493 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
501 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
502 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
503 chdir_init() unless $chdir_init;
505 if ($^O eq 'MSWin32') {
506 # get the full path name *before* the chdir()
507 $newpwd = Win32::GetFullPathName($newdir);
510 return 0 unless CORE::chdir $newdir;
513 return $ENV{'PWD'} = $ENV{'DEFAULT'}
515 elsif ($^O eq 'MacOS') {
516 return $ENV{'PWD'} = cwd();
518 elsif ($^O eq 'MSWin32') {
519 $ENV{'PWD'} = $newpwd;
523 if (ref $newdir eq 'GLOB') { # in case a file/dir handle is passed in
525 } elsif ($newdir =~ m#^/#s) {
526 $ENV{'PWD'} = $newdir;
528 my @curdir = split(m#/#,$ENV{'PWD'});
529 @curdir = ('') unless @curdir;
531 foreach $component (split(m#/#, $newdir)) {
532 next if $component eq '.';
533 pop(@curdir),next if $component eq '..';
534 push(@curdir,$component);
536 $ENV{'PWD'} = join('/',@curdir) || '/';
544 my $start = @_ ? shift : '.';
545 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
547 unless (@cst = stat( $start ))
549 _carp("stat($start): $!");
554 # Make sure we can be invoked on plain files, not just directories.
555 # NOTE that this routine assumes that '/' is the only directory separator.
557 my ($dir, $file) = $start =~ m{^(.*)/(.+)$}
558 or return cwd() . '/' . $start;
560 # Can't use "-l _" here, because the previous stat was a stat(), not an lstat().
562 my $link_target = readlink($start);
563 die "Can't resolve link $start: $!" unless defined $link_target;
566 $link_target = $dir . '/' . $link_target
567 unless File::Spec->file_name_is_absolute($link_target);
569 return abs_path($link_target);
572 return $dir ? abs_path($dir) . "/$file" : "/$file";
582 unless (opendir(PARENT, $dotdots))
584 # probably a permissions issue. Try the native command.
585 return File::Spec->rel2abs( $start, _backtick_pwd() );
587 unless (@cst = stat($dotdots))
589 _carp("stat($dotdots): $!");
593 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
601 unless (defined ($dir = readdir(PARENT)))
603 _carp("readdir($dotdots): $!");
607 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
609 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
612 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
614 } while (defined $dir);
615 chop($cwd) unless $cwd eq '/'; # drop the trailing /
622 local $ENV{PWD} = $ENV{PWD} || ''; # Guard against clobberage
625 my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
627 # Detaint else we'll explode in taint mode. This is safe because
628 # we're not doing anything dangerous with it.
629 ($path) = $path =~ /(.*)/;
630 ($cwd) = $cwd =~ /(.*)/;
633 _croak("$path: No such file or directory");
637 # Make sure we can be invoked on plain files, not just directories.
639 my ($vol, $dir, $file) = File::Spec->splitpath($path);
640 return File::Spec->catfile($cwd, $path) unless length $dir;
643 my $link_target = readlink($path);
644 die "Can't resolve link $path: $!" unless defined $link_target;
646 $link_target = File::Spec->catpath($vol, $dir, $link_target)
647 unless File::Spec->file_name_is_absolute($link_target);
649 return fast_abs_path($link_target);
652 return $dir eq File::Spec->rootdir
653 ? File::Spec->catpath($vol, $dir, $file)
654 : fast_abs_path(File::Spec->catpath($vol, $dir, '')) . '/' . $file;
657 if (!CORE::chdir($path)) {
658 _croak("Cannot chdir to $path: $!");
660 my $realpath = getcwd();
661 if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
662 _croak("Cannot chdir back to $cwd: $!");
667 # added function alias to follow principle of least surprise
668 # based on previous aliasing. --tchrist 27-Jan-00
669 *fast_realpath = \&fast_abs_path;
672 # --- PORTING SECTION ---
674 # VMS: $ENV{'DEFAULT'} points to default directory at all times
675 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
676 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
677 # in the process logical name table as the default device and directory
678 # seen by Perl. This may not be the same as the default device
679 # and directory seen by DCL after Perl exits, since the effects
680 # the CRTL chdir() function persist only until Perl exits.
683 return $ENV{'DEFAULT'};
687 return $ENV{'DEFAULT'} unless @_;
691 my $unix_rpt = _vms_unix_rpt;
693 if (defined &VMS::Filespec::vmsrealpath) {
697 $path_unix = 1 if ($path =~ m#(?<=\^)/#);
698 $path_unix = 1 if ($path =~ /^\.\.?$/);
699 $path_vms = 1 if ($path =~ m#[\[<\]]#);
700 $path_vms = 1 if ($path =~ /^--?$/);
702 my $unix_mode = $path_unix;
704 # In case of a tie, the Unix report mode decides.
705 if ($path_vms == $path_unix) {
706 $unix_mode = $unix_rpt;
708 $unix_mode = 0 if $path_vms;
714 return VMS::Filespec::unixrealpath($path);
719 my $new_path = VMS::Filespec::vmsrealpath($path);
721 # Perl expects directories to be in directory format
722 $new_path = VMS::Filespec::pathify($new_path) if -d $path;
726 # Fallback to older algorithm if correct ones are not
730 my $link_target = readlink($path);
731 die "Can't resolve link $path: $!" unless defined $link_target;
733 return _vms_abs_path($link_target);
736 # may need to turn foo.dir into [.foo]
737 my $pathified = VMS::Filespec::pathify($path);
738 $path = $pathified if defined $pathified;
740 return VMS::Filespec::rmsexpand($path);
744 $ENV{'PWD'} = `cmd /c cd`;
746 $ENV{'PWD'} =~ s:\\:/:g ;
751 if (defined &DynaLoader::boot_DynaLoader) {
752 $ENV{'PWD'} = Win32::GetCwd();
755 chomp($ENV{'PWD'} = `cd`);
757 $ENV{'PWD'} =~ s:\\:/:g ;
761 *_NT_cwd = defined &Win32::GetCwd ? \&_win32_cwd : \&_os2_cwd;
764 if (!defined &Dos::GetCwd) {
765 $ENV{'PWD'} = `command /c cd`;
767 $ENV{'PWD'} =~ s:\\:/:g ;
769 $ENV{'PWD'} = Dos::GetCwd();
775 local $ENV{PATH} = '';
776 local $ENV{CDPATH} = '';
777 local $ENV{ENV} = '';
778 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
784 local $ENV{PATH} = '';
785 local $ENV{CDPATH} = '';
786 local $ENV{ENV} = '';
787 my $path = @_ ? shift : '.';
790 defined( open(REALPATH, '-|') || exec '/usr/bin/fullpath', '-t', $path ) or
791 die "Can't open /usr/bin/fullpath: $!";
792 my $realpath = <REALPATH>;
799 $ENV{'PWD'} = EPOC::getcwd();
804 # Now that all the base-level functions are set up, alias the
805 # user-level functions to the right places
807 if (exists $METHOD_MAP{$^O}) {
808 my $map = $METHOD_MAP{$^O};
809 foreach my $name (keys %$map) {
810 local $^W = 0; # assignments trigger 'subroutine redefined' warning
812 *{$name} = \&{$map->{$name}};
816 # In case the XS version doesn't load.
817 *abs_path = \&_perl_abs_path unless defined &abs_path;
818 *getcwd = \&_perl_getcwd unless defined &getcwd;
820 # added function alias for those of us more
821 # used to the libc function. --tchrist 27-Jan-00
822 *realpath = \&abs_path;