Take the 2-minute tour ×

I want to store a file as /a/b/c/d.txt, but I do not know if any of these directories exist and need to recursively create them if necessary. How can one do this in ruby?

share|improve this question
add comment

4 Answers

up vote 84 down vote accepted

Use mkdir_p:

FileUtils.mkdir_p '/a/b/c'

The _p is a unix holdover for parent/path you can also use the alias mkpath if that makes more sense for you.

FileUtils.mkpath '/a/b/c'

In Ruby 1.9 FileUtils was removed from the core, so you'll have to require 'fileutils'.

share|improve this answer
+1. FileUtils and Pathname are probably the most important tools for Ruby shell scripting. –  Jörg W Mittag Sep 10 '10 at 17:41
add comment

User mkdir_p to create directory recursively

path = "/tmp/a/b/c"

FileUtils.mkdir_p(path) unless File.exists?(path)
share|improve this answer
add comment
 require 'ftools'


share|improve this answer
Thanks for the pointer! The docs seem to prefer FileUtils.mkdir_p, so I took that... –  Jan Limpens Sep 10 '10 at 15:49
add comment

If you are running on unixy machines, don't forget you can always run a shell command under ruby by placing it in backticks.

`mkdir -p /a/b/c`
share|improve this answer
add comment

Your Answer


