Redson
Redson

Reputation: 2140

How do I pass a variable from my local server to a remote server?

I am trying to pass a variable from my local server (location1) to a remote server (location2). The purpose of the code is to copy a file from the remote server from a predefined location. In simpler terms, I want to copy files from location2 to location1 using a predefined path where location1 is on the local server and location2 is a remote server. See the code segment:

 $location1=somewhere/on/local_server
 $location2=somewhere/on/remote_server

 sshpass -p "password" ssh [email protected] 'su -lc "cp -r $location2 $location1";'

The error I get is that both $location1 and $location2 are undefined. Also, I DON'T want to manually type the location paths because they could change at any time and it would be a pain to change them in the code if done manually.

Upvotes: 1

Views: 205

Answers (3)

earizon
earizon

Reputation: 2238

You location1/2 declaration have a syntax error. The "$" must not be used while assigning the value. That's why you get an undefined value:

location1=somewhere/on/local_server
location2=somewhere/on/remote_server

Upvotes: 1

konsolebox
konsolebox

Reputation: 75588

You can try letting the remote shell read variables from input:

location1=somewhere/on/local_server
location2=somewhere/on/remote_server
printf '%s\n%s\n' "$location1" "$location2" | \
    sshpass -p "password" ssh [email protected] 'read location1; read location2; su -lc "cp -r \"$location2\" \"$location1\"";'

Take notice that I added double-quotes to variables. It could work even if pathnames have spaces on them.

Upvotes: 1

anubhava
anubhava

Reputation: 786091

You can do:

sshpass -p "password" ssh [email protected] "su -lc \"cp -r $location2 $location1\""

Upvotes: 3

Related Questions