linux - shell 脚本 : Run function from script over ssh

标签 linux bash shell sh

有没有什么聪明的方法可以通过 ssh 在远程主机上运行本地 Bash 函数?

例如:

#!/bin/bash
#Definition of the function
f () {  ls -l; }

#I want to use the function locally
f

#Execution of the function on the remote machine.
ssh user@host f

#Reuse of the same function on another machine.
ssh user@host2 f

是的,我知道这行不通,但是有没有办法做到这一点?

最佳答案

您可以使用 typeset 命令通过 ssh 使您的功能在远程机器上可用。有几个选项取决于您希望如何运行远程脚本。

#!/bin/bash
# Define your function
myfn () {  ls -l; }

在远程主机上使用该功能:

typeset -f myfn | ssh user@host "$(cat); myfn"
typeset -f myfn | ssh user@host2 "$(cat); myfn"

更好的是,为什么还要管管道:

ssh user@host "$(typeset -f myfn); myfn"

或者您可以使用 HEREDOC:

ssh user@host << EOF
    $(typeset -f myfn)
    myfn
EOF

如果要发送脚本中定义的所有函数,而不仅仅是myfn,只需像这样使用typeset -f:

ssh user@host "$(typeset -f); myfn"

说明

typeset -f myfn 会显示myfn的定义。

cat 将接收函数的定义作为文本,$() 将在当前 shell 中执行它,这将成为远程 shell 中的定义函数。终于可以执行函数了。

最后的代码会在 ssh 执行之前将函数的定义内联。

关于linux - shell 脚本 : Run function from script over ssh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22107610/

相关文章:

linux - 以编程方式在调制解调器上调用一系列号码?

linux - 在其他文件中查找文件名字符串的所有用法

c# - 如何在 C# 中从 IFileDialogCustomize GetEditBoxText() 获取字符串

string - csh 上的自连接字符串

linux - 如何列出非 native 二进制文件的库依赖项?

linux - 使用终端命令在 chrome 中设置主页

bash - 如何在 Bash 中将变量设置为命令的输出?

linux - 重定向本身就是参数的程序的输出

macos - 计算机重新启动时启动的任务卸载

linux - 如何根据另一个文件进行过滤