2 $VERSION = $VERSION = '2.14';
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.
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 =head2 abs_path and friends
75 These functions are exported only on request. They each take a single
76 argument and return the absolute pathname for it. If no argument is
77 given they'll use the current working directory.
83 my $abs_path = abs_path($file);
85 Uses the same algorithm as getcwd(). Symbolic links and relative-path
86 components ("." and "..") are resolved to return the canonical
87 pathname, just like realpath(3).
91 my $abs_path = realpath($file);
93 A synonym for abs_path().
97 my $abs_path = fast_abs_path($file);
99 A more dangerous, but potentially faster version of abs_path.
105 If you ask to override your chdir() built-in function,
109 then your PWD environment variable will be kept up to date. Note that
110 it will only be kept up to date if all packages which use chdir import
120 Since the path seperators are different on some operating systems ('/'
121 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
122 modules wherever portability is a concern.
126 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
127 functions are all aliases for the C<cwd()> function, which, on Mac OS,
128 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
141 use vars qw(@ISA @EXPORT @EXPORT_OK);
143 @ISA = qw/ Exporter /;
144 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
145 @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
147 # sys_cwd may keep the builtin command
149 # All the functionality of this module may provided by builtins,
150 # there is no sense to process the rest of the file.
151 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
156 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
161 *fast_abs_path = \&sys_abspath if defined &sys_abspath;
162 *abs_path = \&fast_abs_path;
163 *realpath = \&fast_abs_path;
164 *fast_realpath = \&fast_abs_path;
172 XSLoader::load('Cwd');
176 # Find the pwd command in the expected locations. We assume these
177 # are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
178 # so everything works under taint mode.
180 foreach my $try ('/bin/pwd',
182 '/QOpenSys/bin/pwd', # OS/400 PASE.
191 # Isn't this wrong? _backtick_pwd() will fail if somenone has
192 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
193 # See [perl #16774]. --jhi
198 sub _carp { require Carp; Carp::carp(@_) }
199 sub _croak { require Carp; Carp::croak(@_) }
201 # The 'natural and safe form' for UNIX (pwd may be setuid root)
203 local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};
204 my $cwd = `$pwd_cmd`;
205 # Belt-and-suspenders in case someone said "undef $/".
207 # `pwd` may fail e.g. if the disk is full
208 chomp($cwd) if defined $cwd;
212 # Since some ports may predefine cwd internally (e.g., NT)
213 # we take care not to override an existing definition for cwd().
215 unless(defined &cwd) {
216 # The pwd command is not available in some chroot(2)'ed environments
217 if( $^O eq 'MacOS' || (defined $ENV{PATH} &&
218 grep { -x "$_/pwd" } split(':', $ENV{PATH})) )
220 *cwd = \&_backtick_pwd;
227 # set a reasonable (and very safe) default for fastgetcwd, in case it
228 # isn't redefined later (20001212 rspier)
231 # By Brandon S. Allbery
233 # Usage: $cwd = getcwd();
243 # Usage: $cwd = &fastcwd;
245 # This is a faster version of getcwd. It's also more dangerous because
246 # you might chdir out of a directory that you can't chdir back into.
249 my($odev, $oino, $cdev, $cino, $tdev, $tino);
253 my($orig_cdev, $orig_cino) = stat('.');
254 ($cdev, $cino) = ($orig_cdev, $orig_cino);
257 ($odev, $oino) = ($cdev, $cino);
258 CORE::chdir('..') || return undef;
259 ($cdev, $cino) = stat('.');
260 last if $odev == $cdev && $oino == $cino;
261 opendir(DIR, '.') || return undef;
263 $direntry = readdir(DIR);
264 last unless defined $direntry;
265 next if $direntry eq '.';
266 next if $direntry eq '..';
268 ($tdev, $tino) = lstat($direntry);
269 last unless $tdev != $odev || $tino != $oino;
272 return undef unless defined $direntry; # should never happen
273 unshift(@path, $direntry);
275 $path = '/' . join('/', @path);
276 if ($^O eq 'apollo') { $path = "/".$path; }
277 # At this point $path may be tainted (if tainting) and chdir would fail.
278 # Untaint it then check that we landed where we started.
279 $path =~ /^(.*)\z/s # untaint
280 && CORE::chdir($1) or return undef;
281 ($cdev, $cino) = stat('.');
282 die "Unstable directory path, current directory changed unexpectedly"
283 if $cdev != $orig_cdev || $cino != $orig_cino;
288 # Keeps track of current working directory in PWD environment var
296 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
297 my($dd,$di) = stat('.');
298 my($pd,$pi) = stat($ENV{'PWD'});
299 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
305 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
308 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
309 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
310 my($pd,$pi) = stat($2);
311 my($dd,$di) = stat($1);
312 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
320 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
321 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
322 chdir_init() unless $chdir_init;
324 if ($^O eq 'MSWin32') {
325 # get the full path name *before* the chdir()
326 $newpwd = Win32::GetFullPathName($newdir);
329 return 0 unless CORE::chdir $newdir;
332 return $ENV{'PWD'} = $ENV{'DEFAULT'}
334 elsif ($^O eq 'MacOS') {
335 return $ENV{'PWD'} = cwd();
337 elsif ($^O eq 'MSWin32') {
338 $ENV{'PWD'} = $newpwd;
342 if ($newdir =~ m#^/#s) {
343 $ENV{'PWD'} = $newdir;
345 my @curdir = split(m#/#,$ENV{'PWD'});
346 @curdir = ('') unless @curdir;
348 foreach $component (split(m#/#, $newdir)) {
349 next if $component eq '.';
350 pop(@curdir),next if $component eq '..';
351 push(@curdir,$component);
353 $ENV{'PWD'} = join('/',@curdir) || '/';
359 # In case the XS version doesn't load.
360 *abs_path = \&_perl_abs_path unless defined &abs_path;
363 my $start = @_ ? shift : '.';
364 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
366 unless (@cst = stat( $start ))
368 _carp("stat($start): $!");
378 unless (opendir(PARENT, $dotdots))
380 _carp("opendir($dotdots): $!");
383 unless (@cst = stat($dotdots))
385 _carp("stat($dotdots): $!");
389 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
397 unless (defined ($dir = readdir(PARENT)))
399 _carp("readdir($dotdots): $!");
403 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
405 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
408 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
410 } while (defined $dir);
411 chop($cwd) unless $cwd eq '/'; # drop the trailing /
416 # added function alias for those of us more
417 # used to the libc function. --tchrist 27-Jan-00
418 *realpath = \&abs_path;
424 my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
426 # Detaint else we'll explode in taint mode. This is safe because
427 # we're not doing anything dangerous with it.
428 ($path) = $path =~ /(.*)/;
429 ($cwd) = $cwd =~ /(.*)/;
431 if (!CORE::chdir($path)) {
432 _croak("Cannot chdir to $path: $!");
434 my $realpath = getcwd();
435 if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
436 _croak("Cannot chdir back to $cwd: $!");
441 # added function alias to follow principle of least surprise
442 # based on previous aliasing. --tchrist 27-Jan-00
443 *fast_realpath = \&fast_abs_path;
446 # --- PORTING SECTION ---
448 # VMS: $ENV{'DEFAULT'} points to default directory at all times
449 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
450 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
451 # in the process logical name table as the default device and directory
452 # seen by Perl. This may not be the same as the default device
453 # and directory seen by DCL after Perl exits, since the effects
454 # the CRTL chdir() function persist only until Perl exits.
457 return $ENV{'DEFAULT'};
461 return $ENV{'DEFAULT'} unless @_;
462 my $path = VMS::Filespec::pathify($_[0]);
465 _croak("Invalid path name $_[0]")
467 return VMS::Filespec::rmsexpand($path);
471 $ENV{'PWD'} = `cmd /c cd`;
473 $ENV{'PWD'} =~ s:\\:/:g ;
478 $ENV{'PWD'} = Win32::GetCwd();
479 $ENV{'PWD'} =~ s:\\:/:g ;
483 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
484 defined &Win32::GetCwd);
486 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
489 if (!defined &Dos::GetCwd) {
490 $ENV{'PWD'} = `command /c cd`;
492 $ENV{'PWD'} =~ s:\\:/:g ;
494 $ENV{'PWD'} = Dos::GetCwd();
500 local $ENV{PATH} = '';
501 local $ENV{CDPATH} = '';
502 local $ENV{ENV} = '';
503 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
509 local $ENV{PATH} = '';
510 local $ENV{CDPATH} = '';
511 local $ENV{ENV} = '';
512 my $path = @_ ? shift : '.';
515 open(REALPATH, '-|', '/usr/bin/fullpath', '-t', $path) or
516 die "Can't open /usr/bin/fullpath: $!";
517 my $realpath = <REALPATH>;
524 $ENV{'PWD'} = EPOC::getcwd();
529 no warnings; # assignments trigger 'subroutine redefined' warning
533 *getcwd = \&_vms_cwd;
534 *fastcwd = \&_vms_cwd;
535 *fastgetcwd = \&_vms_cwd;
536 *abs_path = \&_vms_abs_path;
537 *fast_abs_path = \&_vms_abs_path;
539 elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
540 # We assume that &_NT_cwd is defined as an XSUB or in the core.
543 *fastcwd = \&_NT_cwd;
544 *fastgetcwd = \&_NT_cwd;
545 *abs_path = \&fast_abs_path;
546 *realpath = \&fast_abs_path;
548 elsif ($^O eq 'dos') {
550 *getcwd = \&_dos_cwd;
551 *fastgetcwd = \&_dos_cwd;
552 *fastcwd = \&_dos_cwd;
553 *abs_path = \&fast_abs_path;
555 elsif ($^O =~ m/^(?:qnx|nto)$/ ) {
557 *getcwd = \&_qnx_cwd;
558 *fastgetcwd = \&_qnx_cwd;
559 *fastcwd = \&_qnx_cwd;
560 *abs_path = \&_qnx_abs_path;
561 *fast_abs_path = \&_qnx_abs_path;
563 elsif ($^O eq 'cygwin') {
567 *abs_path = \&fast_abs_path;
568 *realpath = \&abs_path;
570 elsif ($^O eq 'epoc') {
572 *getcwd = \&_epoc_cwd;
573 *fastgetcwd = \&_epoc_cwd;
574 *fastcwd = \&_epoc_cwd;
575 *abs_path = \&fast_abs_path;
577 elsif ($^O eq 'MacOS') {
581 *abs_path = \&fast_abs_path;