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
49 Unfortunately, cwd() tends to break if called under taint mode.
55 A more dangerous version of getcwd(), but potentially faster.
57 It might conceivably chdir() you out of a directory that it can't
58 chdir() you back into. If fastcwd encounters a problem it will return
59 undef but will probably leave you in a different directory. For a
60 measure of extra security, if everything appears to have worked, the
61 fastcwd() function will check that it leaves you in the same directory
62 that it started in. If it has changed it will C<die> with the message
63 "Unstable directory path, current directory changed
64 unexpectedly". That should never happen.
68 my $cwd = fastgetcwd();
70 The fastgetcwd() function is provided as a synonym for cwd().
75 =head2 abs_path and friends
77 These functions are exported only on request. They each take a single
78 argument and return the absolute pathname for it.
84 my $abs_path = abs_path($file);
86 Uses the same algorithm as getcwd(). Symbolic links and relative-path
87 components ("." and "..") are resolved to return the canonical
88 pathname, just like realpath(3).
92 my $abs_path = realpath($file);
94 A synonym for abs_path().
98 my $abs_path = abs_path($file);
100 A more dangerous, but potentially faster version of abs_path.
106 If you ask to override your chdir() built-in function,
110 then your PWD environment variable will be kept up to date. Note that
111 it will only be kept up to date if all packages which use chdir import
121 Since the path seperators are different on some operating systems ('/'
122 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
123 modules wherever portability is a concern.
127 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
128 functions are all aliases for the C<cwd()> function, which, on Mac OS,
129 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
144 our $VERSION = '2.06';
146 use base qw/ Exporter /;
147 our @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
148 our @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
150 # sys_cwd may keep the builtin command
152 # All the functionality of this module may provided by builtins,
153 # there is no sense to process the rest of the file.
154 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
156 if ($^O eq 'os2' && defined &sys_cwd && defined &sys_abspath) {
162 *abs_path = \&sys_abspath;
163 *fast_abs_path = \&abs_path;
164 *realpath = \&abs_path;
165 *fast_realpath = \&abs_path;
171 undef *Cwd::fastcwd; # avoid redefinition warning
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 (qw(/bin/pwd /usr/bin/pwd)) {
188 # The 'natural and safe form' for UNIX (pwd may be setuid root)
190 my $cwd = `$pwd_cmd`;
191 # `pwd` may fail e.g. if the disk is full
193 chomp($cwd) if defined $cwd;
197 # Since some ports may predefine cwd internally (e.g., NT)
198 # we take care not to override an existing definition for cwd().
200 unless(defined &cwd) {
201 # The pwd command is not available in some chroot(2)'ed environments
202 if($^O eq 'MacOS' || grep { -x "$_/pwd" } split(':', $ENV{PATH})) {
203 *cwd = \&_backtick_pwd;
210 # set a reasonable (and very safe) default for fastgetcwd, in case it
211 # isn't redefined later (20001212 rspier)
214 # By Brandon S. Allbery
216 # Usage: $cwd = getcwd();
226 # Usage: $cwd = &fastcwd;
228 # This is a faster version of getcwd. It's also more dangerous because
229 # you might chdir out of a directory that you can't chdir back into.
232 my($odev, $oino, $cdev, $cino, $tdev, $tino);
236 my($orig_cdev, $orig_cino) = stat('.');
237 ($cdev, $cino) = ($orig_cdev, $orig_cino);
240 ($odev, $oino) = ($cdev, $cino);
241 CORE::chdir('..') || return undef;
242 ($cdev, $cino) = stat('.');
243 last if $odev == $cdev && $oino == $cino;
244 opendir(DIR, '.') || return undef;
246 $direntry = readdir(DIR);
247 last unless defined $direntry;
248 next if $direntry eq '.';
249 next if $direntry eq '..';
251 ($tdev, $tino) = lstat($direntry);
252 last unless $tdev != $odev || $tino != $oino;
255 return undef unless defined $direntry; # should never happen
256 unshift(@path, $direntry);
258 $path = '/' . join('/', @path);
259 if ($^O eq 'apollo') { $path = "/".$path; }
260 # At this point $path may be tainted (if tainting) and chdir would fail.
261 # To be more useful we untaint it then check that we landed where we started.
262 $path = $1 if $path =~ /^(.*)\z/s; # untaint
263 CORE::chdir($path) || return undef;
264 ($cdev, $cino) = stat('.');
265 die "Unstable directory path, current directory changed unexpectedly"
266 if $cdev != $orig_cdev || $cino != $orig_cino;
271 # Keeps track of current working directory in PWD environment var
279 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
280 my($dd,$di) = stat('.');
281 my($pd,$pi) = stat($ENV{'PWD'});
282 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
288 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
291 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
292 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
293 my($pd,$pi) = stat($2);
294 my($dd,$di) = stat($1);
295 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
303 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
304 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
305 chdir_init() unless $chdir_init;
307 if ($^O eq 'MSWin32') {
308 # get the full path name *before* the chdir()
309 $newpwd = Win32::GetFullPathName($newdir);
312 return 0 unless CORE::chdir $newdir;
315 return $ENV{'PWD'} = $ENV{'DEFAULT'}
317 elsif ($^O eq 'MacOS') {
318 return $ENV{'PWD'} = cwd();
320 elsif ($^O eq 'MSWin32') {
321 $ENV{'PWD'} = $newpwd;
325 if ($newdir =~ m#^/#s) {
326 $ENV{'PWD'} = $newdir;
328 my @curdir = split(m#/#,$ENV{'PWD'});
329 @curdir = ('') unless @curdir;
331 foreach $component (split(m#/#, $newdir)) {
332 next if $component eq '.';
333 pop(@curdir),next if $component eq '..';
334 push(@curdir,$component);
336 $ENV{'PWD'} = join('/',@curdir) || '/';
342 # In case the XS version doesn't load.
343 *abs_path = \&_perl_abs_path unless defined &abs_path;
346 my $start = @_ ? shift : '.';
347 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
349 unless (@cst = stat( $start ))
351 carp "stat($start): $!";
360 unless (opendir(PARENT, $dotdots))
362 carp "opendir($dotdots): $!";
365 unless (@cst = stat($dotdots))
367 carp "stat($dotdots): $!";
371 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
379 unless (defined ($dir = readdir(PARENT)))
381 carp "readdir($dotdots): $!";
385 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
387 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
390 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
392 } while (defined $dir);
393 chop($cwd) unless $cwd eq '/'; # drop the trailing /
398 # added function alias for those of us more
399 # used to the libc function. --tchrist 27-Jan-00
400 *realpath = \&abs_path;
405 my $path = @_ ? shift : File::Spec->curdir;
406 CORE::chdir($path) || croak "Cannot chdir to $path:$!";
407 my $realpath = getcwd();
408 CORE::chdir($cwd) || croak "Cannot chdir back to $cwd:$!";
412 # added function alias to follow principle of least surprise
413 # based on previous aliasing. --tchrist 27-Jan-00
414 *fast_realpath = \&fast_abs_path;
417 # --- PORTING SECTION ---
419 # VMS: $ENV{'DEFAULT'} points to default directory at all times
420 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
421 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
422 # in the process logical name table as the default device and directory
423 # seen by Perl. This may not be the same as the default device
424 # and directory seen by DCL after Perl exits, since the effects
425 # the CRTL chdir() function persist only until Perl exits.
428 return $ENV{'DEFAULT'};
432 return $ENV{'DEFAULT'} unless @_;
433 my $path = VMS::Filespec::pathify($_[0]);
434 croak("Invalid path name $_[0]") unless defined $path;
435 return VMS::Filespec::rmsexpand($path);
439 $ENV{'PWD'} = `cmd /c cd`;
441 $ENV{'PWD'} =~ s:\\:/:g ;
446 $ENV{'PWD'} = Win32::GetCwd();
447 $ENV{'PWD'} =~ s:\\:/:g ;
451 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
452 defined &Win32::GetCwd);
454 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
457 if (!defined &Dos::GetCwd) {
458 $ENV{'PWD'} = `command /c cd`;
460 $ENV{'PWD'} =~ s:\\:/:g ;
462 $ENV{'PWD'} = Dos::GetCwd();
468 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
474 my $path = @_ ? shift : '.';
475 my $realpath=`/usr/bin/fullpath -t $path`;
481 $ENV{'PWD'} = EPOC::getcwd();
486 no warnings; # assignments trigger 'subroutine redefined' warning
490 *getcwd = \&_vms_cwd;
491 *fastcwd = \&_vms_cwd;
492 *fastgetcwd = \&_vms_cwd;
493 *abs_path = \&_vms_abs_path;
494 *fast_abs_path = \&_vms_abs_path;
496 elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
497 # We assume that &_NT_cwd is defined as an XSUB or in the core.
500 *fastcwd = \&_NT_cwd;
501 *fastgetcwd = \&_NT_cwd;
502 *abs_path = \&fast_abs_path;
503 *realpath = \&fast_abs_path;
505 elsif ($^O eq 'os2') {
506 # sys_cwd may keep the builtin command
507 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
511 *abs_path = \&fast_abs_path;
513 elsif ($^O eq 'dos') {
515 *getcwd = \&_dos_cwd;
516 *fastgetcwd = \&_dos_cwd;
517 *fastcwd = \&_dos_cwd;
518 *abs_path = \&fast_abs_path;
520 elsif ($^O =~ m/^(?:qnx|nto)$/ ) {
522 *getcwd = \&_qnx_cwd;
523 *fastgetcwd = \&_qnx_cwd;
524 *fastcwd = \&_qnx_cwd;
525 *abs_path = \&_qnx_abs_path;
526 *fast_abs_path = \&_qnx_abs_path;
528 elsif ($^O eq 'cygwin') {
532 *abs_path = \&fast_abs_path;
534 elsif ($^O eq 'epoc') {
536 *getcwd = \&_epoc_cwd;
537 *fastgetcwd = \&_epoc_cwd;
538 *fastcwd = \&_epoc_cwd;
539 *abs_path = \&fast_abs_path;
541 elsif ($^O eq 'MacOS') {
545 *abs_path = \&fast_abs_path;