0

I'm working on a bash script that is currently doing the following for multiple variables:

variable1=$(ssh -T user@hostname "command one")  
variable2=$(ssh -T user@hostname "command two")  
variable3=$(ssh -T user@hostname "command three")  
variable4=$(ssh -T user@hostname "command four")  

Is there an easy way (short of sticking the output of multiple commands into a single file and then working with that file) to assign multiple variables from different remote commands on a single ssh connection?

3 Answers 3

3

You can do this by executing all the commands in one SSH command and then getting the output of each back into an array.

Finally, iterate over the array and process as necessary.

Code:

#!/bin/sh

IFS=$'\n'
VARS=`ssh user@host 'echo 1 2; echo 3'`

for A_VAR in $VARS; do
    echo "Out: $A_VAR"
done

Output:

> ./sshtest.sh
Out: 1 2
Out: 3
Sign up to request clarification or add additional context in comments.

Comments

0

No. There is no "return" in bash*, and certainly not over ssh. All you can do is pass data via stdout and stderr.

* all processes and functions have an exit value of an int between 0 and 255, and within a function you can use return to exit with a particular value, but it's not really returning anything like in any other language.

Comments

0

You can get finer control over what you want by "programming the SSH library" (via wrapper). An eg, in Perl, you can use libraries such as Net:SSH::Perl.

my $ssh = Net::SSH::Perl->new("yourhost");
$ssh->login("user1", "pass1");

$ssh->cmd("foo");
$ssh->cmd("bar");

you do multiple commands via a single $ssh instance (contrary to calling the ssh command line tool multiple times using the shell). This is just an example.

Comments

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.