2

I am doing ssh on a machine and executing certain commands.

My last command gives me a variable which I need for a script present locally. However, how do I access that variable after I logout from the machine?

Edit: Please assume that I have already login to the machine.

0

Depends on how you want to do it. Getting the output of a single command within an interactive session isn't that easy to do automatically. You could of course just copy and paste the output from the terminal. But you could also save the output to a file on the remote, and then do something like var=$(ssh remote "cat file.with.var"), or run the command that generates the final output similarly: var=$(ssh remote "somecommand").

Or, if you want to do it directly from an interactive session, you could rig up an expect script to do it.

  • This saving the variable inside the file looks nice to me. – Anant Simran Singh Mar 15 '17 at 12:23
3

You can capture the output of the command you executed remotely to a local variable on the client machine.

myvar="foo" 
echo "$myvar"
myvar=$(ssh user@hostname 'myvar="bar"; echo $myvar')
echo "$myvar"

Note the single quotes around the remote command: 'myvar="bar"; echo $myvar'. This prevents the shell from expanding $myvar locally before sending the command to the remote host for evaluation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.