Home > OS >  How do I get the result of a command from a remote server using ssh?
How do I get the result of a command from a remote server using ssh?

Time:06-07

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?

CodePudding user response:

Print null delimited file list remotely, sort it by reverse major version, and patch version, so the latest is listed first

read -r -d '' latest_archive < <(
  ssh \
    -o UserKnownHostsFile=/dev/null \
    -o StrictHostKeyChecking=no \
    -o PreferredAuthentications=publickey \
    [email protected] \
    printf '%s\\0' '/my/dir/file-*[[:digit:]].tar.xz' | sort -zt- -k2nr,3nr
)

How it works:

  • printf '%s\\0' '/my/dir/file-*[[:digit:]].tar.xz': Prints null-delimited list of files matching the pattern.
  • | sort -zt- -k2nr,3nr: Pipe to sort -z null-delimited entries, -t- with dash - as field delimiter, -k2nr,3nr on 2nd field numerically, largest first, combined with 3rd field numerically and also largest first.

CodePudding user response:

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

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