Unable to use local and remote variables within a heredoc or command over SSH

后端 未结 2 1773
南方客
南方客 2020-12-18 09:36

Below is an example of a ssh script using a heredoc (the actual script is more complex). Is it possible to use both local and remote variables within an SSH heredoc or comma

相关标签:
2条回答
  • 2020-12-18 09:53

    You need to escape the $ sign if you don't want the variable to be expanded:

    $ x=abc
    $ bash <<EOF
    > x=def
    > echo $x   # This expands x before sending it to bash. Bash will see only "echo abc"
    > echo \$x  # This lets bash perform the expansion. Bash will see "echo $x"
    > EOF
    abc
    def
    

    So in your case:

    ssh user@host bash << EOF
    # run script with output...
    REMOTE_PID=$(cat $FILE_NAME)
    echo \$REMOTE_PID
    EOF
    

    Or alternatively you can just use a herestring with single quotes:

    $ x=abc
    $ bash <<< '
    > x=def
    > echo $x  # This will not expand, because we are inside single quotes
    > '
    def
    
    0 讨论(0)
  • 2020-12-18 10:00
    remote_user_name=user
    instance_ip=127.0.0.1
    external=$(ls /home/)
    
    ssh -T -i ${private_key}  -l ${remote_user_name} ${instance_ip} << END
      internal=\$(ls /home/)
      echo "\${internal}"
      echo "${external}"
    END
    
    0 讨论(0)
提交回复
热议问题