2
votes

I'm writing a script trying to both scp files to and from a remote server, and want to use the remote server variable within the script rather than hardcode the directory into the script, as this will be used in different environments with different paths.

So for example the hardcoded version to fetch a file ...

scp user@remotehost:/userbase/filefolder/file1 .

but lets say on the remote host "userbase" was set as a $BASEHOME variable. I know a standard

scp user@remotehost:$BASEHOME/filefolder/file1 .

won't work as it tries to evaluate $BASEHOME on the host sending the scp

I had a look around and its been suggested online that something similar to the following may work

scp user@remotehost:$(ssh user@remotehost "echo \$BASEHOME")/filefolder/file1 .

But this errors - I tried printf instead of echo, single quotes and no \before $BASEHOME but none work, with errors similar to the following appearing (as if its not picking up the variable)

scp: /filefolder/file1: No such file or directory

Is it possible to use a remote variable when scp'ing?

Thanks!

1

1 Answers

0
votes

No, it's not possible to use remote shell variables with scp.

Workaround 1: get the remote variable once and reuse it later:

BASEHOME=$(ssh user@remotehost 'echo $BASEHOME')
scp user@remotehost:$BASEHOME/filefolder/file1 .

Workaround 2: cat the file on the remote side and redirect to local file:

ssh user@remotehost 'cat $BASEHOME/filefolder/file1' > file1