将方法传递给 heredocs

Passing methods to heredocs

我需要通过ssh在大量主机上调用一些代码。

我尝试使用所谓的 heredocs

function verifyFiles {
    ...
}

...

ssh user@$server <<-SSH
    cd $DIRECTORY
    verifyFiles
    createSum
    copyFiles
SSH

ssh user@server2 <<-SSH
    cd $DIRECTORY
    verifyFiles
    verifySums
SSH
...

不幸的是,服务器端不知道以这种方式使用的函数。

有没有一种优雅的方法可以使用这些函数而不将它们粘贴到每个函数中heredoc

PS。每个主机上的代码调用略有不同,但使用相同的函数集。我真的很想在代码中拥有每个方法定义的 1 个副本。

PS2。当然,如果有更好的方法调用这段代码,我不必使用heredocs

由于 here-documents 进行了各种扩展,您可以通过参数替换而不是函数调用来实现您的目标:

VERIFYFILES='ls; df'

ssh user@$server <<-SSH
    cd $DIRECTORY
    $VERIFYFILES
SSH

如果你有一个本地函数 fooX 在每个 hostX 上远程执行,你可以通过 ssh 在各自的主机上定义和执行它,如下所示:

#!/bin/bash

function foo1() {
    echo foo
}

function foo2() {
    echo f0o
}

function remotefn() {
    # echo the function definition:
    type "" | tail -n +2
    # echo the function call:
    echo ""
}

while read user host fn
do
    # remotely execute function definition and the function itself:
    remotefn "$fn" | ssh "$user"@"$host"
done <<END
user1 host1 foo1
user2 host2 foo2
END

注意循环后的heredoc如何灵活地将函数映射到用户和主机。 ssh 将在各自的主机上读取并执行 remotefn 提供的每个函数定义和函数调用。

这个怎么样?

funs='
  foo() { echo "foo"; }
  bar() { local a; for a in "$@"; do echo "$a"; done; }
'
# eval "$funs"  # if you want the functions locally as well
ssh user@$server1 <<-____HERE
    cd $DIRECTORY
    $funs
    foo && bar some args
____HERE

不是一个特别令人满意的解决方案,但我相信它可以满足您的要求。