gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:37:56 28 4
gpt4 key购买 nike

有没有什么聪明的方法可以通过 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com