Reputation: 31
I'm trying to capture output of a script (resides on a remote server) run over SSH into a variable, below is my code:
ssh username@hostname << EOF
variable=`./script_on_remote_server.sh`
echo $variable
EOF
When i run the above script, nothing gets stored in the variable and echo of that variable returns nothing.
What am I doing wrong?
Upvotes: 3
Views: 5197
Reputation: 5501
For ./script_on_remote_server.sh
to be evaluated in the remote machine. You'll need to quote << EOF
with << 'EOF'
and add -T
to your ssh
command.
ssh -T username@hostname << 'EOF'
variable=`./script_on_remote_server.sh`
echo $variable
EOF
Upvotes: 1
Reputation: 2156
I'll start by showing one way of achieving this:
variable=`echo ./script_on_remote_server.sh | ssh username@hostname`
Or if you're using bash, I prefer this syntax:
variable=$(echo ./script_on_remote_server.sh | ssh username@hostname)
It's a little difficult to tell from your post, but it looks like you were trying to do the following:
ssh username@hostname <<EOF
variable=./script_on_remote_server.sh
echo $variable
EOF
However, there are a few misunderstandings here. variable=command
is not the correct syntax for assigning the output of the command to a variable; in fact, it doesn't even run the command, it merely assigns the literal value command
to variable
. What you want is variable=`command`
or (in bash syntax) variable=$(command)
. Also, I presume that your goal is to have variable
available to the shell on the local machine. Declaring variable
in code to be run on the remote machine is not the way to do that. ;) Even if you did this:
ssh username@hostname <<EOF
variable=`./script`
echo $variable
EOF
This is just a less efficient way of running the command on the remote host as usual, because variable
gets lost immediately:
echo ./script | ssh username@hostname
Also, note that the ssh
command accepts a command to run as an additional argument, so you can abbreviate the whole thing to:
variable=`ssh username@hostname ./script_on_remote_server`
Upvotes: 3