capistrano run problem

I am trying to use run to reload a small program in after_deploy, it
goes something like this:

        run <<-CMD
                if [[ -f #{shared_path}/pids/program.pid ]]; then
                        pid=$(cat #{shared_path}/pids/program.pid)
                        if [[ $pid ]]; then
                                kill -9 $pid
                        fi
                fi
                cd #{release_path}/vendor/cli && ./program.rb"
        CMD

When I run cap deploy it sends something like:
  * executing "if [[ -f /home/yyy.com/shared/pids/dprogram.pid ]]; then
\n\t\t\tpid=$(cat /home/yyy.com/shared/pids/program.pid)\n\t\t\tif
[[ $pid ]]; then\n\t\t\t\tkill -9 $pid\n\t\t\tfi\n\t\tfi\n\t cd /
home/yyy.com/releases/20070323023501/vendor/cli && ./program.rb"

Which returns something like:
** [out :: www.yyy.com] bash: -c: line 3: syntax error near
unexpected token `then'
** [out :: www.yyy.com] bash: -c: line 3: `
kill -9 $pid\'
    command finished

Those commands work if not passed via capistrano. Any ideas on how to
fix this?

- Radu

run <<-CMD
                 if [[ -f #{shared_path}/pids/program.pid ]]; then
                         pid=$(cat #{shared_path}/pids/program.pid) ;
                         if [[ $pid ]]; then
                                 kill -9 $pid ;
                         fi ;
                 fi ;
                 (cd #{release_path}/vendor/cli && ./program.rb)"
         CMD

Try it with the extra ';' and the ( ) around the last command. The whole string has to be parsable by the shell as if you typed it on a single line. The ()'s force a subshell for the last part and keep the && from associating in a way you might not expect (perhaps not now, but later if you add other commands).

You can probably replace -f with -s, "cat" with "<", and remove the 'if/fi' around the kill command.
Heck, you might as well try:

         run <<-CMD
            if [[ -s #{shared_path}/pids/program.pid ]]; then
                kill -9 $(< #{shared_path}/pids/program.pid) ;
            fi ;
            (cd #{release_path}/vendor/cli && ./program.rb)"
         CMD

(but try the small changes first to see for yourself)

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com