2

I want to use the variables of ssh in shell script. suppose I have some variable a whose value I got inside the ssh and now I want to use that variable outside the ssh in the shell itself, how can I do this ?

ssh my_pc2 <<EOF
<.. do some operations ..>
a=$(ls -lrt | wc -l)
echo \$a
EOF
echo $a

In the above example first echo print 10 inside ssh prints 10 but second echo $a prints nothing.

2 Answers 2

1

I would refine the last answer by defining some special syntax for passing the required settings back, e.g. "#SET var=value"

We could put the commands (that we want to run within the ssh session) in a cmdFile file like this:

a=`id`
b=`pwd`
echo "#SET a='$a'"
echo "#SET b='$b'"

And the main script would look like this:

#!/bin/bash

# SSH, run the remote commands, and filter anything they passed back to us
ssh user@host <cmdFile | grep "^#SET " | sed 's/#SET //' >vars.$$

# Source the variable settings that were passed back
. vars.$$
rm -f vars.$$

# Now we have the variables set
echo "a = $a"
echo "b = $b"

If you're doing this for lots of variables, you can add a function to cmdFile, to simplify/encapsulate your special syntax for passing data back:

passvar()
{
  var=$1
  val=$2
  val=${val:-${!var}}
  echo "#SET ${var}='${val}'"
}

a=`id`
passvar a
b=`pwd`
passvar b

You might need to play with quotes when the values include whitespace.

Sign up to request clarification or add additional context in comments.

Comments

0

A script like this could be used to store all the output from SSH into a variable:

#!/bin/bash

VAR=$(ssh user@host << _EOF
id
_EOF)

echo "VAR=$VAR"

it produces the output:

VAR=uid=1000(user) gid=1000(user) groups=1000(user),4(adm),10(wheel)

2 Comments

hmmm but if inside ssh there are about 1000 lines and 100 output variables but I want to use 10 particular variable of ssh, then how can I use it..?
Either you can run a script on the remote side that only outputs what you're interested in, or if the data is too complex, you can gather the information in a large string, base64 encode it and output that, decoding and parsing it on the client side. You might want to try fabric (docs.fabfile.org/en/1.8) for complicated scenarios

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.