Search code examples
linuxbashsshquoting

Bash resolve variables locally before used in a remote context


I've got a script that sets some environment variables on a remote machine, but I've got a problem with some variables being resolved in the remote machine's context. These variables must be resolved before being sent to the remote.

#!/bin/bash
devIP=$(ifconfig | sed -En \'s/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
#10.0.0.1

ssh -A ubuntu@remote '\
export variable="$devIP";\
echo $variable'
#Will echo blank as it is trying to resolve $devIP under the remote context.

How can I properly feed the script executor's IP into an environment variable on the remote machine?


Solution

  • Consider the following command

    ssh -A ubuntu@remote "\
    export variable=$devIP;\
    echo \$variable"
    

    Here variable substitution is performed on the local machine for variable $devIP in the command line argument

    export variable=$devIP; echo \$variable
    

    because of the double quotes.

    Yet variable $variable is protected from local substitution with a backslash.