You may try something like this:
scp file host2@host2_address:$(ssh host2@host2_address 'printf $FOO')
In order to resolve the value of the variable
$(ssh host2@host2_address 'printf $FOO'), the shell will internally execute the command
ssh host2@host2_address 'printf $FOO', and take whatever this command prints as the value of the variable, which is then substituted into the outer
scp command. It is, of course, clear that you have to fetch the variable
$FOO from host2, because host1 simply does not know it. One way to fetch it is using
ssh as in the above command.
You have to have some kind of public-key authentication working, so that the inner
ssh command works without any further user input. Otherwise, because of the inner
ssh and the outer
scp, you would be prompted for the password twice.
You should ensure that the inner
ssh command prints out nothing but the variable
$FOO. Try it out on its own before using it in the outer
scp command and make sure it works.
For some reason I do not fully understand, when I tested the command that I wrote above, it would not work as expected because the fetched variable would contain some weird control prefix. For instance, when I tried to copy something to the remote
$HOME, it would try yo copy it to
\033k$HOME\033\\/home/user instead of simply
/home/user. I had to use the following to get it to work:
scp file host2@host2_address:$(ssh host2@host2_address 'printf $FOO' | cut -d\\ -f2)
$HOME in my particular case, of course.
This is a quick (as it's rather short) and dynamic (as it will fetch the variable on the fly) solution I came up with. However, particularly because of the last point, I think it would be more reliable to have a script that fetches the remote variables by first printing them to a file. More precisely, that script on host1 would connect to host2, remotely print the output of
printenv to some file at host2, fetch that file from host2, parse it, and export the values to local environment variables. For example, the variable
$FOO on host2 could be put into a variable
$HOST2_FOO on host1. The following script would do this:
ssh host2@host2_address 'printenv > host2_vars.txt'
scp host2@host2_address:host2_vars.txt .
#ssh host2@host2_address 'rm host2_vars.txt' #if you like to clean up
eval $(cat host2_vars.txt | perl -pe 's/^(.*)=(.*)$/export HOST2_$1="$2"/g')
Of course, you would have to execute that script before the