ssh remote variable assignment?

前端 未结 1 1574
广开言路
广开言路 2021-02-20 10:12

The following does not work for me:

ssh user@remote.server \"k=5; echo $k;\"

it just returns an empty line.

How can I assign a variabl

相关标签:
1条回答
  • 2021-02-20 11:07

    Given this invocation:

    ssh user@remote.server "k=5; echo $k;"
    

    the local shell is expanding $k (which most likely isn't set) before it is executing ssh .... So the command that actually gets passed to the remote shell once the connection is made is k=5; echo ; (or k=5; echo something_else_entirely; if k is actually set locally).

    To avoid this, escape the dollar sign like this:

    ssh user@remote.server "k=5; echo \$k;"
    

    Alternatively, use single quotes instead of double quotes to prevent the local expansion. However, while that would work on this simple example, you may actually want local expansion of some variables in the command that gets sent to the remote side, so the backslash-escaping is probably the better route.

    For future reference, you can also type set -x in your shell to echo the actual commands that are being executed as a help for troubleshooting.

    0 讨论(0)
提交回复
热议问题