1File::Path(3)         User Contributed Perl Documentation        File::Path(3)
2
3
4

NAME

6       File::Path - Create or remove directory trees
7

VERSION

9       2.18 - released November 4 2020.
10

SYNOPSIS

12           use File::Path qw(make_path remove_tree);
13
14           @created = make_path('foo/bar/baz', '/zug/zwang');
15           @created = make_path('foo/bar/baz', '/zug/zwang', {
16               verbose => 1,
17               mode => 0711,
18           });
19           make_path('foo/bar/baz', '/zug/zwang', {
20               chmod => 0777,
21           });
22
23           $removed_count = remove_tree('foo/bar/baz', '/zug/zwang', {
24               verbose => 1,
25               error  => \my $err_list,
26               safe => 1,
27           });
28
29           # legacy (interface promoted before v2.00)
30           @created = mkpath('/foo/bar/baz');
31           @created = mkpath('/foo/bar/baz', 1, 0711);
32           @created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
33           $removed_count = rmtree('foo/bar/baz', 1, 1);
34           $removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
35
36           # legacy (interface promoted before v2.06)
37           @created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
38           $removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
39

DESCRIPTION

41       This module provides a convenient way to create directories of
42       arbitrary depth and to delete an entire directory subtree from the
43       filesystem.
44
45       The following functions are provided:
46
47       make_path( $dir1, $dir2, .... )
48       make_path( $dir1, $dir2, ...., \%opts )
49           The "make_path" function creates the given directories if they
50           don't exist before, much like the Unix command "mkdir -p".
51
52           The function accepts a list of directories to be created. Its
53           behaviour may be tuned by an optional hashref appearing as the last
54           parameter on the call.
55
56           The function returns the list of directories actually created
57           during the call; in scalar context the number of directories
58           created.
59
60           The following keys are recognised in the option hash:
61
62           mode => $num
63               The numeric permissions mode to apply to each created directory
64               (defaults to 0777), to be modified by the current "umask". If
65               the directory already exists (and thus does not need to be
66               created), the permissions will not be modified.
67
68               "mask" is recognised as an alias for this parameter.
69
70           chmod => $num
71               Takes a numeric mode to apply to each created directory (not
72               modified by the current "umask"). If the directory already
73               exists (and thus does not need to be created), the permissions
74               will not be modified.
75
76           verbose => $bool
77               If present, will cause "make_path" to print the name of each
78               directory as it is created. By default nothing is printed.
79
80           error => \$err
81               If present, it should be a reference to a scalar.  This scalar
82               will be made to reference an array, which will be used to store
83               any errors that are encountered.  See the "ERROR HANDLING"
84               section for more information.
85
86               If this parameter is not used, certain error conditions may
87               raise a fatal error that will cause the program to halt, unless
88               trapped in an "eval" block.
89
90           owner => $owner
91           user => $owner
92           uid => $owner
93               If present, will cause any created directory to be owned by
94               $owner.  If the value is numeric, it will be interpreted as a
95               uid; otherwise a username is assumed. An error will be issued
96               if the username cannot be mapped to a uid, the uid does not
97               exist or the process lacks the privileges to change ownership.
98
99               Ownership of directories that already exist will not be
100               changed.
101
102               "user" and "uid" are aliases of "owner".
103
104           group => $group
105               If present, will cause any created directory to be owned by the
106               group $group.  If the value is numeric, it will be interpreted
107               as a gid; otherwise a group name is assumed. An error will be
108               issued if the group name cannot be mapped to a gid, the gid
109               does not exist or the process lacks the privileges to change
110               group ownership.
111
112               Group ownership of directories that already exist will not be
113               changed.
114
115                   make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
116
117       mkpath( $dir )
118       mkpath( $dir, $verbose, $mode )
119       mkpath( [$dir1, $dir2,...], $verbose, $mode )
120       mkpath( $dir1, $dir2,..., \%opt )
121           The mkpath() function provide the legacy interface of make_path()
122           with a different interpretation of the arguments passed.  The
123           behaviour and return value of the function is otherwise identical
124           to make_path().
125
126       remove_tree( $dir1, $dir2, .... )
127       remove_tree( $dir1, $dir2, ...., \%opts )
128           The "remove_tree" function deletes the given directories and any
129           files and subdirectories they might contain, much like the Unix
130           command "rm -rf" or the Windows commands "rmdir /s" and "rd /s".
131
132           The function accepts a list of directories to be removed. (In point
133           of fact, it will also accept filesystem entries which are not
134           directories, such as regular files and symlinks.  But, as its name
135           suggests, its intent is to remove trees rather than individual
136           files.)
137
138           remove_tree()'s behaviour may be tuned by an optional hashref
139           appearing as the last parameter on the call.  If an empty string is
140           passed to "remove_tree", an error will occur.
141
142           NOTE:  For security reasons, we strongly advise use of the hashref-
143           as-final-argument syntax -- specifically, with a setting of the
144           "safe" element to a true value.
145
146               remove_tree( $dir1, $dir2, ....,
147                   {
148                       safe => 1,
149                       ...         # other key-value pairs
150                   },
151               );
152
153           The function returns the number of files successfully deleted.
154
155           The following keys are recognised in the option hash:
156
157           verbose => $bool
158               If present, will cause "remove_tree" to print the name of each
159               file as it is unlinked. By default nothing is printed.
160
161           safe => $bool
162               When set to a true value, will cause "remove_tree" to skip the
163               files for which the process lacks the required privileges
164               needed to delete files, such as delete privileges on VMS. In
165               other words, the code will make no attempt to alter file
166               permissions. Thus, if the process is interrupted, no filesystem
167               object will be left in a more permissive mode.
168
169           keep_root => $bool
170               When set to a true value, will cause all files and
171               subdirectories to be removed, except the initially specified
172               directories. This comes in handy when cleaning out an
173               application's scratch directory.
174
175                   remove_tree( '/tmp', {keep_root => 1} );
176
177           result => \$res
178               If present, it should be a reference to a scalar.  This scalar
179               will be made to reference an array, which will be used to store
180               all files and directories unlinked during the call. If nothing
181               is unlinked, the array will be empty.
182
183                   remove_tree( '/tmp', {result => \my $list} );
184                   print "unlinked $_\n" for @$list;
185
186               This is a useful alternative to the "verbose" key.
187
188           error => \$err
189               If present, it should be a reference to a scalar.  This scalar
190               will be made to reference an array, which will be used to store
191               any errors that are encountered.  See the "ERROR HANDLING"
192               section for more information.
193
194               Removing things is a much more dangerous proposition than
195               creating things. As such, there are certain conditions that
196               "remove_tree" may encounter that are so dangerous that the only
197               sane action left is to kill the program.
198
199               Use "error" to trap all that is reasonable (problems with
200               permissions and the like), and let it die if things get out of
201               hand. This is the safest course of action.
202
203       rmtree( $dir )
204       rmtree( $dir, $verbose, $safe )
205       rmtree( [$dir1, $dir2,...], $verbose, $safe )
206       rmtree( $dir1, $dir2,..., \%opt )
207           The rmtree() function provide the legacy interface of remove_tree()
208           with a different interpretation of the arguments passed. The
209           behaviour and return value of the function is otherwise identical
210           to remove_tree().
211
212           NOTE:  For security reasons, we strongly advise use of the hashref-
213           as-final-argument syntax, specifically with a setting of the "safe"
214           element to a true value.
215
216               rmtree( $dir1, $dir2, ....,
217                   {
218                       safe => 1,
219                       ...         # other key-value pairs
220                   },
221               );
222
223   ERROR HANDLING
224       NOTE:
225           The following error handling mechanism is consistent throughout all
226           code paths EXCEPT in cases where the ROOT node is nonexistent.  In
227           version 2.11 the maintainers attempted to rectify this
228           inconsistency but too many downstream modules encountered problems.
229           In such case, if you require root node evaluation or error checking
230           prior to calling "make_path" or "remove_tree", you should take
231           additional precautions.
232
233       If "make_path" or "remove_tree" encounters an error, a diagnostic
234       message will be printed to "STDERR" via "carp" (for non-fatal errors)
235       or via "croak" (for fatal errors).
236
237       If this behaviour is not desirable, the "error" attribute may be used
238       to hold a reference to a variable, which will be used to store the
239       diagnostics. The variable is made a reference to an array of hash
240       references.  Each hash contain a single key/value pair where the key is
241       the name of the file, and the value is the error message (including the
242       contents of $! when appropriate).  If a general error is encountered
243       the diagnostic key will be empty.
244
245       An example usage looks like:
246
247         remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
248         if ($err && @$err) {
249             for my $diag (@$err) {
250                 my ($file, $message) = %$diag;
251                 if ($file eq '') {
252                     print "general error: $message\n";
253                 }
254                 else {
255                     print "problem unlinking $file: $message\n";
256                 }
257             }
258         }
259         else {
260             print "No error encountered\n";
261         }
262
263       Note that if no errors are encountered, $err will reference an empty
264       array.  This means that $err will always end up TRUE; so you need to
265       test @$err to determine if errors occurred.
266
267   NOTES
268       "File::Path" blindly exports "mkpath" and "rmtree" into the current
269       namespace. These days, this is considered bad style, but to change it
270       now would break too much code. Nonetheless, you are invited to specify
271       what it is you are expecting to use:
272
273         use File::Path 'rmtree';
274
275       The routines "make_path" and "remove_tree" are not exported by default.
276       You must specify which ones you want to use.
277
278         use File::Path 'remove_tree';
279
280       Note that a side-effect of the above is that "mkpath" and "rmtree" are
281       no longer exported at all. This is due to the way the "Exporter" module
282       works. If you are migrating a codebase to use the new interface, you
283       will have to list everything explicitly. But that's just good practice
284       anyway.
285
286         use File::Path qw(remove_tree rmtree);
287
288       API CHANGES
289
290       The API was changed in the 2.0 branch. For a time, "mkpath" and
291       "rmtree" tried, unsuccessfully, to deal with the two different calling
292       mechanisms. This approach was considered a failure.
293
294       The new semantics are now only available with "make_path" and
295       "remove_tree". The old semantics are only available through "mkpath"
296       and "rmtree". Users are strongly encouraged to upgrade to at least 2.08
297       in order to avoid surprises.
298
299       SECURITY CONSIDERATIONS
300
301       There were race conditions in the 1.x implementations of File::Path's
302       "rmtree" function (although sometimes patched depending on the OS
303       distribution or platform). The 2.0 version contains code to avoid the
304       problem mentioned in CVE-2002-0435.
305
306       See the following pages for more information:
307
308           http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
309           http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
310           http://www.debian.org/security/2005/dsa-696
311
312       Additionally, unless the "safe" parameter is set (or the third
313       parameter in the traditional interface is TRUE), should a "remove_tree"
314       be interrupted, files that were originally in read-only mode may now
315       have their permissions set to a read-write (or "delete OK") mode.
316
317       The following CVE reports were previously filed against File-Path and
318       are believed to have been addressed:
319
320       •   <http://cve.circl.lu/cve/CVE-2004-0452>
321
322       •   <http://cve.circl.lu/cve/CVE-2005-0448>
323
324       In February 2017 the cPanel Security Team reported an additional
325       vulnerability in File-Path.  The chmod() logic to make directories
326       traversable can be abused to set the mode on an attacker-chosen file to
327       an attacker-chosen value.  This is due to the time-of-check-to-time-of-
328       use (TOCTTOU) race condition
329       (<https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>) between
330       the stat() that decides the inode is a directory and the chmod() that
331       tries to make it user-rwx.  CPAN versions 2.13 and later incorporate a
332       patch provided by John Lightsey to address this problem.  This
333       vulnerability has been reported as CVE-2017-6512.
334

DIAGNOSTICS

336       FATAL errors will cause the program to halt ("croak"), since the
337       problem is so severe that it would be dangerous to continue. (This can
338       always be trapped with "eval", but it's not a good idea. Under the
339       circumstances, dying is the best thing to do).
340
341       SEVERE errors may be trapped using the modern interface. If the they
342       are not trapped, or if the old interface is used, such an error will
343       cause the program will halt.
344
345       All other errors may be trapped using the modern interface, otherwise
346       they will be "carp"ed about. Program execution will not be halted.
347
348       mkdir [path]: [errmsg] (SEVERE)
349           "make_path" was unable to create the path. Probably some sort of
350           permissions error at the point of departure or insufficient
351           resources (such as free inodes on Unix).
352
353       No root path(s) specified
354           "make_path" was not given any paths to create. This message is only
355           emitted if the routine is called with the traditional interface.
356           The modern interface will remain silent if given nothing to do.
357
358       No such file or directory
359           On Windows, if "make_path" gives you this warning, it may mean that
360           you have exceeded your filesystem's maximum path length.
361
362       cannot fetch initial working directory: [errmsg]
363           "remove_tree" attempted to determine the initial directory by
364           calling "Cwd::getcwd", but the call failed for some reason. No
365           attempt will be made to delete anything.
366
367       cannot stat initial working directory: [errmsg]
368           "remove_tree" attempted to stat the initial directory (after having
369           successfully obtained its name via "getcwd"), however, the call
370           failed for some reason. No attempt will be made to delete anything.
371
372       cannot chdir to [dir]: [errmsg]
373           "remove_tree" attempted to set the working directory in order to
374           begin deleting the objects therein, but was unsuccessful. This is
375           usually a permissions issue. The routine will continue to delete
376           other things, but this directory will be left intact.
377
378       directory [dir] changed before chdir, expected dev=[n] ino=[n], actual
379       dev=[n] ino=[n], aborting. (FATAL)
380           "remove_tree" recorded the device and inode of a directory, and
381           then moved into it. It then performed a "stat" on the current
382           directory and detected that the device and inode were no longer the
383           same. As this is at the heart of the race condition problem, the
384           program will die at this point.
385
386       cannot make directory [dir] read+writeable: [errmsg]
387           "remove_tree" attempted to change the permissions on the current
388           directory to ensure that subsequent unlinkings would not run into
389           problems, but was unable to do so. The permissions remain as they
390           were, and the program will carry on, doing the best it can.
391
392       cannot read [dir]: [errmsg]
393           "remove_tree" tried to read the contents of the directory in order
394           to acquire the names of the directory entries to be unlinked, but
395           was unsuccessful. This is usually a permissions issue. The program
396           will continue, but the files in this directory will remain after
397           the call.
398
399       cannot reset chmod [dir]: [errmsg]
400           "remove_tree", after having deleted everything in a directory,
401           attempted to restore its permissions to the original state but
402           failed. The directory may wind up being left behind.
403
404       cannot remove [dir] when cwd is [dir]
405           The current working directory of the program is /some/path/to/here
406           and you are attempting to remove an ancestor, such as /some/path.
407           The directory tree is left untouched.
408
409           The solution is to "chdir" out of the child directory to a place
410           outside the directory tree to be removed.
411
412       cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting.
413       (FATAL)
414           "remove_tree", after having deleted everything and restored the
415           permissions of a directory, was unable to chdir back to the parent.
416           The program halts to avoid a race condition from occurring.
417
418       cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
419           "remove_tree" was unable to stat the parent directory after having
420           returned from the child. Since there is no way of knowing if we
421           returned to where we think we should be (by comparing device and
422           inode) the only way out is to "croak".
423
424       previous directory [parent-dir] changed before entering [child-dir],
425       expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)
426           When "remove_tree" returned from deleting files in a child
427           directory, a check revealed that the parent directory it returned
428           to wasn't the one it started out from. This is considered a sign of
429           malicious activity.
430
431       cannot make directory [dir] writeable: [errmsg]
432           Just before removing a directory (after having successfully removed
433           everything it contained), "remove_tree" attempted to set the
434           permissions on the directory to ensure it could be removed and
435           failed. Program execution continues, but the directory may possibly
436           not be deleted.
437
438       cannot remove directory [dir]: [errmsg]
439           "remove_tree" attempted to remove a directory, but failed. This may
440           be because some objects that were unable to be removed remain in
441           the directory, or it could be a permissions issue. The directory
442           will be left behind.
443
444       cannot restore permissions of [dir] to [0nnn]: [errmsg]
445           After having failed to remove a directory, "remove_tree" was unable
446           to restore its permissions from a permissive state back to a
447           possibly more restrictive setting. (Permissions given in octal).
448
449       cannot make file [file] writeable: [errmsg]
450           "remove_tree" attempted to force the permissions of a file to
451           ensure it could be deleted, but failed to do so. It will, however,
452           still attempt to unlink the file.
453
454       cannot unlink file [file]: [errmsg]
455           "remove_tree" failed to remove a file. Probably a permissions
456           issue.
457
458       cannot restore permissions of [file] to [0nnn]: [errmsg]
459           After having failed to remove a file, "remove_tree" was also unable
460           to restore the permissions on the file to a possibly less
461           permissive setting. (Permissions given in octal).
462
463       unable to map [owner] to a uid, ownership not changed");
464           "make_path" was instructed to give the ownership of created
465           directories to the symbolic name [owner], but "getpwnam" did not
466           return the corresponding numeric uid. The directory will be
467           created, but ownership will not be changed.
468
469       unable to map [group] to a gid, group ownership not changed
470           "make_path" was instructed to give the group ownership of created
471           directories to the symbolic name [group], but "getgrnam" did not
472           return the corresponding numeric gid. The directory will be
473           created, but group ownership will not be changed.
474

SEE ALSO

476       •   File::Remove
477
478           Allows files and directories to be moved to the Trashcan/Recycle
479           Bin (where they may later be restored if necessary) if the
480           operating system supports such functionality. This feature may one
481           day be made available directly in "File::Path".
482
483       •   File::Find::Rule
484
485           When removing directory trees, if you want to examine each file to
486           decide whether to delete it (and possibly leaving large swathes
487           alone), File::Find::Rule offers a convenient and flexible approach
488           to examining directory trees.
489

BUGS AND LIMITATIONS

491       The following describes File::Path limitations and how to report bugs.
492
493   MULTITHREADED APPLICATIONS
494       File::Path "rmtree" and "remove_tree" will not work with multithreaded
495       applications due to its use of "chdir".  At this time, no warning or
496       error is generated in this situation.  You will certainly encounter
497       unexpected results.
498
499       The implementation that surfaces this limitation will not be changed.
500       See the File::Path::Tiny module for functionality similar to File::Path
501       but which does not "chdir".
502
503   NFS Mount Points
504       File::Path is not responsible for triggering the automounts, mirror
505       mounts, and the contents of network mounted filesystems.  If your NFS
506       implementation requires an action to be performed on the filesystem in
507       order for File::Path to perform operations, it is strongly suggested
508       you assure filesystem availability by reading the root of the mounted
509       filesystem.
510
511   REPORTING BUGS
512       Please report all bugs on the RT queue, either via the web interface:
513
514       <http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
515
516       or by email:
517
518           bug-File-Path@rt.cpan.org
519
520       In either case, please attach patches to the bug report rather than
521       including them inline in the web post or the body of the email.
522
523       You can also send pull requests to the Github repository:
524
525       <https://github.com/rpcme/File-Path>
526

ACKNOWLEDGEMENTS

528       Paul Szabo identified the race condition originally, and Brendan O'Dea
529       wrote an implementation for Debian that addressed the problem.  That
530       code was used as a basis for the current code. Their efforts are
531       greatly appreciated.
532
533       Gisle Aas made a number of improvements to the documentation for 2.07
534       and his advice and assistance is also greatly appreciated.
535

AUTHORS

537       Prior authors and maintainers: Tim Bunce, Charles Bailey, and David
538       Landgren <david@landgren.net>.
539
540       Current maintainers are Richard Elberger <riche@cpan.org> and James
541       (Jim) Keenan <jkeenan@cpan.org>.
542

CONTRIBUTORS

544       Contributors to File::Path, in alphabetical order by first name.
545
546       <bulkdd@cpan.org>
547       Charlie Gonzalez <itcharlie@cpan.org>
548       Craig A. Berry <craigberry@mac.com>
549       James E Keenan <jkeenan@cpan.org>
550       John Lightsey <john@perlsec.org>
551       Nigel Horne <njh@bandsman.co.uk>
552       Richard Elberger <riche@cpan.org>
553       Ryan Yee <ryee@cpan.org>
554       Skye Shaw <shaw@cpan.org>
555       Tom Lutz <tommylutz@gmail.com>
556       Will Sheppard <willsheppard@github>
557
559       This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren,
560       James Keenan and Richard Elberger 1995-2020. All rights reserved.
561

LICENSE

563       This library is free software; you can redistribute it and/or modify it
564       under the same terms as Perl itself.
565
566
567
568perl v5.38.0                      2023-07-20                     File::Path(3)
Impressum