How can you check to see if a file exists (on the remote server) in Capistrano?

Teflon Ted picture Teflon Ted · Nov 2, 2009 · Viewed 22.4k times · Source

Like many others I've seen in the Googleverse, I fell victim to the File.exists? trap, which of course checks your local file system, not the server you are deploying to.

I found one result that used a shell hack like:

if [[ -d #{shared_path}/images ]]; then ...

but that doesn't sit well with me, unless it were wrapped nicely in a Ruby method.

Has anybody solved this elegantly?

Answer

Matt Connolly picture Matt Connolly · Jan 2, 2014

In capistrano 3, you can do:

on roles(:all) do
  if test("[ -f /path/to/my/file ]")
    # the file exists
  else
    # the file does not exist
  end
end

This is nice because it returns the result of the remote test back to your local ruby program and you can work in simpler shell commands.