0

I tried many things today to have ssh start a screen session which executes a command. The goal is to run a command on a remote machine and to be able to see the output and to detach and reattach latter. I want to do it from within a script without any interaction except detaching the screen session to close. No satisfying solution so far.

ssh -t ${host} "\
    source ~/.bashrc; \
    echo \"done.\"; \
    cd \"$exedir\"; \
    if [ \$? -ne 0 ]; then \
        echo \"could not cd into directory\"; \
        exit 1; \
    fi; \
    echo \"executing remotexe.sh ...\"; \
    screen -S "remotexe" -t "remotexe" -R "nice -n$prio ./remotexe.sh ${exeparams[@]}";"

Some of the problems I encounter are related to the strange ways to pass commands to screen/ssh/bash which interfere with arguments and options (I don't quite understand why they do not use -- to interpret whatever follows as commands with arguments). The above version almost works. The remaining difficulty is that commands in remotexe.sh (in particular make) obviously miss exports and definitions from .bashrc. This is why I tried to include the source ~/.bashrc. I tried to add similar commands or explicit exports to remotexe.sh but it behaves as if it was executed by /bin/sh. If I do a conventional ssh login I can immediately run the remotexe.sh script without error. I also tried adding shell -$SHELL to my .screenrc.

Where is the mistake in this solution? How can I correct it?

highsciguy
  • 2,569
  • 3
  • 34
  • 59
  • There seem to be some problems with the escaping of `"` in the last line. Try quoting the entire snippet with `'` instead of `"` to save yourself some of these escaping headaches. – Thomas Nov 24 '12 at 16:35
  • Then the variables in the string will not be evaluated, right? I could of course excape the `"` in the string. – highsciguy Nov 24 '12 at 16:37
  • Pardon me. Then do it the other way round: use `"` to surround the snippet and `'` for any string within it. – Thomas Nov 24 '12 at 16:38
  • The command above is passing `-n$prio` as an argument to ssh. Remove the `"` before `nice` and the one before the `;` – William Pursell Nov 24 '12 at 16:39
  • There's no need to escape newlines in double quoted strings an reasonable shells. Also, you can do `cd $exedir || exit 1` There's no need to print an error message: `cd` will print one for you. – William Pursell Nov 24 '12 at 16:41

1 Answers1

0

I haven't tested your code at all, and will not vouch for the sanity of this, but you definitely have a quoting error. Try:

ssh -t ${host} "
    source ~/.bashrc;
    echo done.;
    cd \"$exedir\" || exit 1;
    echo executing remotexe.sh ...;
    screen -S remotexe -t remotexe -R nice -n$prio ./remotexe.sh ${exeparams[@]};"
William Pursell
  • 204,365
  • 48
  • 270
  • 300