echo
测试显示我的命令行变量正在运行,但如何传递它们,导出它们,以便在嵌入式expect
中使用?
#!/bin/bash
echo name of script is $0
echo host is $1
echo hostusername is $2
echo hostpassword is $3
expect -c 'spawn ssh -l $2 $1 < ./sf-wall_scp_bash.sh
sleep 2
expect {
"(yes/no)? " {send "yes\n"}
exp_continue
}
expect {
"?assword" {send "$3\r"}
}
sleep 1
'
如果使用expect
shebang调用,它就像
#!/usr/bin/expect
set host [lindex $argv 0]
set hostusername [lindex $argv 1]
set hostpassword [lindex $argv 2]
spawn ssh -l $hostusername $host
sleep 2
expect {
"(yes/no)? " {send "yes\n"}
exp_continue
}
expect {
"?assword" {send "$hostpassword\r"}
}
sleep 1
...按预期工作。我需要使用bash
并嵌入expect
,因为脚本需要调用bash特定的命令,函数,内置变量......否则只需使用第二个例子就可以了,但是它不是。
我已尝试声明并导出命令行参数变量,并将上面第一个示例中的$ 1,$ 2,$ 3分别更改为声明和导出的变量名称,这在我实际声明的另一个脚本中有效脚本中的变量......区别在于它们不是命令行参数。
host=$1
export host
hostusername=$2
export hostusername
hostpassword=$3
export hostpassword
以及只是导出它们
export host
export hostusername
export hostpassword
并尝试上面的第一个例子。没有变化,expect
继续声称
无法读取“X”:没有这样的变量
在另一个bash脚本中,我能够通过BOTH声明它们然后导出它们来成功导出变量,如上例所示。但是,将bash
命令行参数变量传递给expect
答案 0 :(得分:5)
嵌套引号的代码不易编写和读取。我建议你使用shell的 here-document 语法。例如(演示将bash
vars传递给expect
的两种方式):
$ cat foo.sh
arg1=$1
export arg2=$2
expect << END
puts $arg1
puts \$env(arg2)
END
$ bash foo.sh hello world
hello
world
$
我更喜欢shell中的export var
并使用$env(var)
引用它,因为您不必担心var
是否有某些特殊字符(例如'
其中包含},"
或空格。