hawarden_
hawarden_

Reputation: 2160

Shell: save ssh command result to local variable

I have a ssh command that sends back a number:

ssh ${user}@${hostname} "wc -l < ${workspace}/logs" 

where ${user},${hostname},${workspace}are variables.

Now I want to save the result to a local variable called lines, I tried:

lines=${ssh ${user}@${hostname} "wc -l < ${workspace}/logs" }

But it does not work, why?

Upvotes: 2

Views: 2210

Answers (2)

Brae
Brae

Reputation: 514

Your command should be wrapped in "()" not "{}" when assigning fetching the result to a variable. Also, the others are just variables not commands so don't need a wrapper (assuming they are defined in a script or something).

lines=$(ssh $user@$hostname "wc -l < $workspace/logs")

Upvotes: 3

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

You should use $() to get the result of command, not ${} (in bash at least). The line below assumes that workspace is a variable defined on the host executing the lines=, not on the remote (if it was on the remote you would need to escape the $: \${workspace}/logs

lines=$(ssh ${user}@${hostname} "wc -l < ${workspace}/logs" )

Upvotes: 0

Related Questions