I am trying to write a script which automatically checks out or updates a Subversion URL based on whether a specified directory exists or not.
For some reason, my code isn't working and always returns true even if it's false:
def directory_exists?(directory)
return false if Dir[directory] == nil
true
end
What am I doing wrong?
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
You could use Kernel#test
:
test ?d, 'some directory'
it gets it's origins from https://ss64.com/bash/test.html
you will notice bash test
has this flag -d
to test if a directory exists
-d file True if file is a Directory. [[ -d demofile ]]
You can also use Dir::exist?
like so:
Dir.exist?('Directory Name')
Returns
true
if the 'Directory Name' is a directory,false
otherwise.1
All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:
File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true
Source: Stackoverflow.com