Function 使用shell脚本中的函数调用执行命令
我正在尝试使用shell脚本中的函数调用执行命令。当我将命令作为该函数的参数传递给该函数时,它不起作用 功能定义:Function 使用shell脚本中的函数调用执行命令,function,shell,Function,Shell,我正在尝试使用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
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
我得到的结果是:
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
我得到的结果和我预期的一样:
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
在第一种情况下,将命令作为函数参数传递时,请帮助我了解错误所在。如果我没有错,双引号内的任何参数都将替换为大括号。因此,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
EXPECT_OUTPUT=($(expect ssh_exec.expect $1 $2 $3))
ExecuteCommand oracle@192.168.***.*** password123 srvctl status database -d mydb