Search code examples
bashshelleofheredoc

Saving a remote variable locally with heredoc through ssh


I am trying to run a local function remotely on a machine and retrieve the values of multiple variables of this function in a local function.

The first line of the heredoc section enables me to run the function remotely by defining it on the remote machine.

With the local machine named localmach and the remote machine named remotemach

#! /bin/bash

arr=()

scanHost()
{
  arr+=("$(hostname)")
  tmpResult=$(hostname)
}

scanHost

ssh user@remotemach "bash -s --" <<EOF
$(typeset -f scanHost)
tmpResult=$tmpResult
scanHost
EOF

echo "Local array -> ${arr[@]}"
echo "Local echo  -> $tmpResult"

The snippet above returns

Local array -> localmach
Local echo  -> localmach

But what I need is

Local array -> localmach remotemach
Local echo  -> remotemach

In words, I need the value of the remote tmpResult AND the array arr stored locally.

Addendum : Here I make the command hostname as an example, but in reality I am "scanning" a remote host and generate a JSON string that I store in the tmpResult variable. If I encounter problems during the scan, I append a string explaining the issue in arr. This way in my final json I can list all the problems encountered during the scan of multiple hosts.


Solution

  • You need to collect the result of ssh command :

    #! /bin/bash
    
    scanHost()
    {
      tmpResult=$(hostname)
    }
    
    scanHost
    
    tmpResult=$(ssh user@remotemach "bash -s" <<EOF
    $(typeset -f scanHost)
    scanHost
    echo "\$tmpResult"
    EOF
    )
    
    echo "Local echo -> $tmpResult"
    

    New Version

    #! /bin/bash
    
    arr=()
    
    scanHost()
    {
      arr+=("$(hostname)")
      tmpResult=$(hostname)
    }
    
    scanHost
    
    eval "$(ssh user@remotemach "bash -s" <<EOF
    $(typeset -f scanHost)
    $(declare -p arr)
    scanHost
    declare -p arr
    declare -p tmpResult
    EOF
    )"
    
    echo "Local array -> ${arr[@]}"
    echo "Local echo  -> $tmpResult"
    

    Use eval with caution due to side effects.