Lakerda
Lakerda

Reputation: 139

How to save commands output into a variable via ssh in bash

I want to save an output of a piped sequence of commands into a variable on a remote server. I'm trying to do it via ssh like this:

ssh $host "kernel_ver=`sudo yum list kernel --showduplicates | grep 7.$os_rel | tr -s " " | cut -d" " -f2 | head -n1`; echo $kernel_ver"

I'm getting this errors:

Error: No matching Packages to list
ssh: Could not resolve hostname kernel_ver= ; echo : Name or service not known

$os_rel is a variable in my script containing a number.

I tried different syntax like: "$( )" to capture the output and it still doesn't work.

Upvotes: 1

Views: 508

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

If you use double quotes to surround everything then the backticks will be evaluated by the local shell rather than the remote one. So will the variable reference $kernel_ver. Use single quotes to disable both.

ssh $host 'kernel_ver=`sudo yum list kernel --showduplicates | grep 7.$os_rel | tr -s " " | cut -d" " -f2 | head -n1`; echo $kernel_ver'

If $os_rel is a local variable that you do want expanded then you'll need to temporarily leave single quotes.

ssh $host 'kernel_ver=`sudo yum list kernel --showduplicates | grep 7.'"$os_rel"' | tr -s " " | cut -d" " -f2 | head -n1`; echo $kernel_ver'

Upvotes: 1

Related Questions