shell脚本:从脚本通过ssh运行功能 [英] Shell script: Run function from script over ssh
问题描述
有没有什么聪明的方法通过ssh运行bash的纸条本地功能?
Is there any clever way to run a local function from the bash scrip over ssh?
例如:
#!/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
是的,我知道这是行不通的,是有办法做到这一点?
Yeah, I know it doesn't work, is there a way to achieve this?
推荐答案
有一个简单的方法来完成它。
There is an easy way to accomplish it.
#!/bin/bash
#Definition of the function
f () { ls -l; }
要在远程主机上使用的功能:
To use the function in the remote host:
typeset -f | ssh user@host "$(cat);f"
到另一个远程机器上使用:
To use on another remote machine:
typeset -f | ssh user@host2 "$(cat);f"
但
好,为什么用管打扰
Better yet, why bother with pipe
ssh user@host "$(typeset -f); f"
解释。
排版-f将显示脚本中定义的功能。
typeset -f will display the functions defined within the script.
猫
将接收功能作为文本的定义和 $()
将在当前执行它外壳,这将成为远程shell定义的功能。最后的功能可以被执行。
cat
will receive the definition of the function as a text and $()
will execute it in the current shell which will become a defined function in the remote shell. Finally the function can be executed.
最后code将使的函数的定义SSH执行前的内联。
The last code will put the definition of the functions inline before ssh execution.
这篇关于shell脚本:从脚本通过ssh运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!