is it possible to use variables in remote ssh command?

前端 未结 2 822
暖寄归人
暖寄归人 2020-11-30 13:46

I\'d like to execute several commands in sequence on a remote machine, and some of the later commands depend on earlier ones. In the simplest possible example I get this:

2条回答
  •  失恋的感觉
    2020-11-30 14:26

    With some inspiration from chepner, I now have a solution that works, but only when called from a bash shell or bash script. It doesn't work from tcsh.

    ssh my_server "bash -c 'echo this is \$HOSTNAME; abc=2; echo abc is \$abc;'"
    

    Based on this, the code below is a local script which runs jabref on a remote server (although with X-forwarding by default and passwordless authentication the user can't tell it's remote):

    #!/bin/bash
    if [ -f "$1" ]
    then
        fname_start=$(echo ${1:0:4})
        if [ "$fname_start" = "/tmp" ]
        then
            scp $1 my_server:$1
            ssh my_server "bash -c 'source load_module jdk; source load_module jabref; java_exe=\$(which java); jabref_exe=\$(which jabref); jabref_dir=\$(echo \${jabref_exe%/bin/jabref});eval \$(java -jar \$jabref_dir/jabref.jar $1)'" &
        else
            echo input argument must be a file in /tmp.
    else
        echo this function requires 1 argument
    fi
    

    and this is the 1-line script load_module, since modulecmd sets environment variables and I couldn't figure out how to do that without sourcing a script.

    eval `/path/to/modulecmd bash load $1`;
    

    I also looked at heredocs, inspired by How to use SSH to run a shell script on a remote machine? and http://tldp.org/LDP/abs/html/here-docs.html. The nice part is that it works even from tcsh. I got this working from the command line, but not inside a script. That's probably easy enough to fix, but I've got a solution now so I'm happy :-)

    ssh my_server 'bash -s' << EOF
    echo this is \$HOSTNAME; abc=2; echo abc is \$abc;
    EOF
    

提交回复
热议问题