is it possible to use variables in remote ssh command?

前端 未结 2 830
暖寄归人
暖寄归人 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:30

    In this example

    ssh my_server "echo this is my_server; abc=2;"
    

    abc is set on the remote side, so it should be clear why it is not set on your local machine.

    In the next example,

    ssh my_server "echo this is my_server; abc=2; echo abc is $abc"
    

    your local shell tries to expand $abc in the argument before it is ever sent to the remote host. A slight modification would work as you expected:

    ssh my_server 'echo this is my_server; abc=2; echo abc is $abc'
    

    The single quotes prevent your local shell from trying to expand $abc, and so the literal text makes it to the remote host.


    To finally address your real question, try this:

    jabref_dir=$( ssh my_server 'jabref_exe=$(which jabref); jabref_dir=$(dirname $jabref_exe);
                   java -jar $jabref_dir/../jabref.jar > /dev/null; echo $jabref_dir' )
    

    This will run the quoted string as a command on your remote server, and output exactly one string: $jabref_dir. That string is captured and stored in a variable on your local host.

提交回复
热议问题