我正在尝试使用shell脚本中的函数调用来执行命令。当我将命令作为该函数的参数传递给该函数时,它不起作用。
功能定义:
function ExecuteCommand() (
# $1: User@Host
# $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 oracle@192.168.***.*** password123 "srvctl status database -d mydb"
我得到的输出是:
spawn ssh oracle@192.168.***.*** {srvctl status database -d mydb}
oracle@192.168.***.***'s password:
bash: {srvctl: command not found
但是当我没有将命令作为函数的参数传递时,它完美地运行:
那种情况下的函数定义:
function ExecuteCommand() (
# $1: User@Host
# $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 oracle@192.168.***.*** password123
我得到的输出就像我预期的那样:
spawn ssh oracle@192.168.***.*** srvctl status database -d mydb
oracle@192.168.***.***'s password:
Instance mydb1 is running on node mydb1
Instance mydb2 is running on node mydb2
Instance mydb3 is running on node mydb3
请在第一种情况下将命令作为函数参数传递给我,帮助我解决问题。
答案 0 :(得分:0)
如果我没有错,那么双引号中“期望”的任何参数都会被花括号替换。因此,expect命令变得像:
expect ssh_exec.expect oracle@192.168.***.*** {srvctl status database -d mydb}
使shell将“{srvctl”解释为命令。
尝试使用它:
EXPECT_OUTPUT=($(expect ssh_exec.expect $*))
而不是
EXPECT_OUTPUT=($(expect ssh_exec.expect $1 $2 $3))
并将您的功能称为:
ExecuteCommand oracle@192.168.***.*** password123 srvctl status database -d mydb