views:

2201

answers:

4

I'm using Capistrano run a remote task. My task looks like this:

task :my_task do
  run "my_command"
end

My problem is that if my_command has an exit status != 0, then Capistrano considers it failed and exits. How can I make capistrano keep going when exit when the exit status is not 0? I've changed my_command to my_command;echo and it works but it feels like a hack.

+1  A: 

You'll need to patch the Capistrano code if you want it to do different things with the exit codes; it's hard-coded to raise an exception if the exit status is not zero.

Here's the relevant portion of lib/capistrano/command.rb. The line that starts with if (failed... is the important one. Basically it says if there are any nonzero return values, raise an error.

# Processes the command in parallel on all specified hosts. If the command
# fails (non-zero return code) on any of the hosts, this will raise a
# Capistrano::CommandError.
def process!
  loop do
    break unless process_iteration { @channels.any? { |ch| !ch[:closed] } }
  end

  logger.trace "command finished" if logger

  if (failed = @channels.select { |ch| ch[:status] != 0 }).any?
    commands = failed.inject({}) { |map, ch| (map[ch[:command]] ||= []) << ch[:server]; map }
    message = commands.map { |command, list| "#{command.inspect} on #{list.join(',')}" }.join("; ")
    error = CommandError.new("failed: #{message}")
    error.hosts = commands.values.flatten
    raise error
  end

  self
end
Sarah Mei
A: 

I just redirect STDERR and STDOUT to /dev/null, so your

run "my_command"

becomes

run "my_command > /dev/null 2> /dev/null"

this works for standard unix tools pretty well, where, say, cp or ln could fail, but you don't want to halt deployment on such a failure.

Terry
+2  A: 

The +grep+ command exits non-zero based on what it finds. In the use case where you care about the output but don't mind if it's empty, you'll discard the exit state silently:

run %Q{bash -c 'grep #{escaped_grep_command_args} ; true' }

Normally, I think the first solution is just fine -- I'd make it document itself tho:

cmd = "my_command with_args escaped_correctly"
run %Q{bash -c '#{cmd} || echo "Failed: [#{cmd}] -- ignoring."'}
mrflip
+4  A: 

The simplest way is to just append true to the end of your comamnd.

  task :my_task do
    run "my_command"
  end

Becomes

  task :my_task do
    run "my_command; true"
  end
mthorley
Not sure what capistano is but I found my way here due to the same problem with bash. And then you can use "my_command || true" instead of "my_command; true"
Zitrax