2

I am creating a remote variable whose value I want to assign to a local variable in unix. Here is the code #!/bin/bash

INPUT= "test"
ssh [email protected]
"if [ -s $INPUT ];
then
    date=\`date\`
    remote= $INPUT.date
    $INPUT= \$remote
else
    mkdir $INPUT
fi"

Basically I am assigning a value to a local variable. Upon ssh to a remote server, I am checking whether a non-empty directory by the name of "test" exists. If it does, then I am appending a time-stamp to the $INPUT local variable. The code works fine till line 8 "remote= $INPUT.date". But the assignment of the remote variable \$remote to the local variable $INPUT does not. What am I doing wrong. Thanks for the help.

2
  • I don't think the remote shell can change your local shell's variables, no. Instead the script you run remotely could e.g. print the value of $remote or nothing, and you could e.g. capture this into a variable locally with backticks and then use that to conditionally update INPUT?
    – Rup
    Feb 24, 2014 at 1:32
  • So how do I do this? Export the remote variable to a file locally? I tried "cat \$remote > file.txt" but file.txt gets made on the remote server, since the whole code ("if .... fi") is working on the server.
    – user45270
    Feb 24, 2014 at 2:17

2 Answers 2

5

As Rup said, the remote shell cannot set your local shell variables. You need to capture the remote variable by printing it out, and using command substitution. This SSH command will do what you are trying to do, then it will echo the amended value you want to store in $INPUT:

INPUT="test"
ssh user@remotehost "if [ -s $INPUT ]; then 
timestamp=\$(date)
echo "${INPUT}.\${timestamp}"
fi"

Output:

test.Monday, 24 February 2014 11:26:41 GMT

If you want $INPUT to be changed, you then need to use the whole SSH command as a command substitution:

INPUT="test"
INPUT=$(ssh user@remotehost "if [ -s $INPUT ]; then 
timestamp=\$(date)
echo "${INPUT}.\${timestamp}"
fi")

Output:

$> echo $INPUT
test.Monday, 24 February 2014 11:27:47 GMT

Similarly, if you want to store a variable in a txt file, this will store it on the remote host:

ssh user@remotehost "echo \$remote > file.txt"

This will store it locally:

ssh user@remotehost "echo \$remote" > file.txt
0

You can solve it with:

SERVERS=('server1@host1' 'server2@host2' 'server3@host3')
for server in "${SERVERS[@]}"
do
       remoteVariable=$(ssh $server "echo \$remote")
       echo $remoteVariable
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.