Saturday, July 9, 2022

[SOLVED] How do I get the result of a command from a remote server using ssh?

Issue

I am working in Linux bash (version 16.04.4 LTS). I am using ssh to connect to a remote server where I want to find for a specific file from a list of files (most recent file version) and then retrieve only the version. For example, considering this files on the remote server (server.com):

file-30.0-2.tar.xz
file-30.0-3.tar.xz
file-30.0-4.tar.xz
file-30.0-5.tar.xz
file-30.0-7.tar.xz
file-30.0-10.tar.xz

If I login directly in the remote server and If I try the following command it works.

ls file-*.tar.xz | sort -V | tail -n1 | grep -o '[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+'

Output: 30.0-10

As I am working from another server I am using ssh to connect to remote server like this:

#!/bin/bash
set -euxo pipefail

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey [email protected] "cd /myDir; \\
  ls file-*.tar.xz | sort -V | tail -n1 | grep -o '[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+')"

This command it's working and I get the same output as before (30.0-10).

But I want to be able to pass that result (30.0-10) to outside the script and use it in the local server.

Any ideas?


Solution

Simply assign the output of your script to a variable and later use that variable:

result="$(./yourscript)"
echo "Result from SSH = $result"


Answered By - knittl
Answer Checked By - Katrina (WPSolving Volunteer)