首页 > 解决方案 > 通过 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_cdtfrominstall_prelibrary可以,但create_wallet_and_keys会出错command not found。为什么create_wallet_and_keys不像其他函数那样在远程主机上调用?我希望在远程主机上调用的第一个函数是install_prelibrary,然后从此函数调用其他两个。请纠正我。

标签: bashfunctionshellremote-host

解决方案


如果没有确切地看到生成的脚本是什么样子,就不可能真正解决这个问题。

但我会将您的逻辑分解为一个脚本,该脚本被复制到目的地并在那里执行,以及一个执行复制和评估的简单脚本。

#!/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其读入变量中。


推荐阅读