bash - 通过 bash 脚本将函数从函数调用到远程主机不起作用
问题描述
我正在编写一个 bash 脚本来登录远程主机并通过它调用多个函数。从 ssh 远程脚本调用install_prelibrary
并从此调用其他两个函数。下面是我的脚本:
#!/bin/bash
source ~/shell/config.sh
install_prelibrary () {
wget https://github.com/EOSIO/eos/releases/download/v2.0.0/eosio_2.0.0-1-ubuntu-18.04_amd64.deb --no-check-certificate > /dev/null 2>&1;
if [ $? -ne 0 ]; then
printf "\n\nError downloading Ubuntu Binary file\n\n"
exit 0;
else
install_cdt
create_wallet_and_keys
fi
}
install_cdt(){
#some commands
}
create_wallet_and_keys(){
#some commands
}
SCRIPT="$(cat ~/shell/config.sh) ; $(declare -f) ; install_prelibrary"
for i in ${!genesishost[*]} ; do
printf "\t=========== node ${genesishost[i]} ===========\n\n"
SCR=${SCRIPT/PASSWORD/${password}}
sshpass -p ${password} ssh -l ${username} ${genesishost[i]} "${SCR}"
done
配置文件
#!/bin/bash
username=abc
password=abc
genesishost=(192.168.*.*);
当我使用 运行这个脚本时bash main.sh
,首先,create_wallet_and_keys
被调用。我不知道为什么?因为我没有在任何地方手动调用这个函数。其次是install_prelibrary
然后 install_cdt
。调用install_cdt
frominstall_prelibrary
可以,但create_wallet_and_keys
会出错command not found
。为什么create_wallet_and_keys
不像其他函数那样在远程主机上调用?我希望在远程主机上调用的第一个函数是install_prelibrary
,然后从此函数调用其他两个。请纠正我。
解决方案
如果没有确切地看到生成的脚本是什么样子,就不可能真正解决这个问题。
但我会将您的逻辑分解为一个脚本,该脚本被复制到目的地并在那里执行,以及一个执行复制和评估的简单脚本。
#!/bin/bash
script=$(cat <<\____HERE
install_prelibrary () {
# Notice also refactoring; comments below
if wget https://github.com/EOSIO/eos/releases/download/v2.0.0/eosio_2.0.0-1-ubuntu-18.04_amd64.deb --no-check-certificate > /dev/null 2>&1; then
: pass
else
rc=$?
# Write errors to standard error, exit with an actual failure code
printf "Error downloading Ubuntu Binary file\n" >&2
exit $rc
fi
install_cdt
create_wallet_and_keys
}
install_cdt(){
#some commands
}
create_wallet_and_keys(){
#some commands
}
____HERE
)
SCRIPT="$(cat ~/shell/config.sh); $script; install_prelibrary"
for i in ${!genesishost[*]} ; do
printf "\t=========== node ${genesishost[i]} ===========\n\n"
SCR=${SCRIPT/PASSWORD/"$password"}
sshpass -p "$password" ssh -l "$username" "${genesishost[i]}" "${SCR}"
done
如果您也需要在本地评估函数,那么让脚本自行读取并不难;或者只是将代码存储在外部文件中,并将source
其读入变量中。
推荐阅读
- mysql - 返回错误但完成插入的 SQLSTATE
- css - Grid Gap Boostrap - 如何修复?
- python - Keras 的准确率低于任何分类器
- java - 将文件输入 Java 以生成新的输出文件
- jquery - 选择一个 Jquery UI 工具提示动画
- python - 布尔条件为 True,但 while 循环仍未中断
- javascript - 将点击侦听器添加到 vue 中的列表元素的问题
- sql-server - 使用 Tableau 创建仪表板的 Hive 性能?
- angular - Auth Guard 在无效 url 的情况下导航到基本 url
- php - PHP in_array 与正则表达式干草堆数组