1
我想在shell脚本中使用函数调用执行命令。当我将该命令作为该函数的参数传递给该函数时,它不起作用。在shell脚本中使用函数调用执行命令
函数定义:
function ExecuteCommand() (
# $1: [email protected]
# $2: Password
# $3: Command to execute
# Collect current IFS value
OLD_IFS=$IFS
# Set IFS value to new line feed
IFS=$'\n'
#Execute the command and capture the output
EXPECT_OUTPUT=($(expect ssh_exec.expect $1 $2 $3))
#Print the output
OUTPUT_LINE_COUNT=${#EXPECT_OUTPUT[@]}
for ((OUTPUT_LINE_INDEX=0; OUTPUT_LINE_INDEX<OUTPUT_LINE_COUNT; OUTPUT_LINE_INDEX++)) ;
do
echo ${EXPECT_OUTPUT[$OUTPUT_LINE_INDEX]}
done
# Get back to the original IFS
IFS=$OLD_IFS
)
函数调用:
ExecuteCommand [email protected]***.*** password123 "srvctl status database -d mydb"
和输出我得到的是:
spawn ssh [email protected]***.*** {srvctl status database -d mydb}
[email protected]***.***'s password:
bash: {srvctl: command not found
但是,当我不及格作为一个命令功能rgument,它完美的作品:
功能定义在这种情况下:
function ExecuteCommand() (
# $1: [email protected]
# $2: Password
# Collect current IFS value
OLD_IFS=$IFS
# Set IFS value to new line feed
IFS=$'\n'
#Execute the command and capture the output
EXPECT_OUTPUT=($(expect ssh_exec.expect $1 $2 srvctl status database -d mydb))
#Print the output
OUTPUT_LINE_COUNT=${#EXPECT_OUTPUT[@]}
for ((OUTPUT_LINE_INDEX=0; OUTPUT_LINE_INDEX<OUTPUT_LINE_COUNT; OUTPUT_LINE_INDEX++)) ;
do
echo ${EXPECT_OUTPUT[$OUTPUT_LINE_INDEX]}
done
# Get back to the original IFS
IFS=$OLD_IFS
)
函数调用:
ExecuteCommand [email protected]***.*** password123
而且我得到的输出,正如我所料:
spawn ssh [email protected]***.*** srvctl status database -d mydb
[email protected]***.***'s password:
Instance mydb1 is running on node mydb1
Instance mydb2 is running on node mydb2
Instance mydb3 is running on node mydb3
在第一种情况下,请在此处传递命令作为函数参数时,请帮助我解决错误。
谢谢你这么多大师,它的工作原理! – user1684896