如何在bash脚本中将参数传递给内联期望?

时间:2016-03-29 12:53:04

标签: bash expect

我正在创建一个shell脚本来自动安装具有自己的安装程序脚本的软件,但我不想向用户提示。所以我用期望回答所说的剧本。现在我有以下内容:

expect $package -c 'set timeout -1
set package [lindex $argv 0]
spawn sh install_pipeline
expect "Where should I install the software packages ? *"
send "/usr/local/$package\r"
expect "Where should I install the pipeline calibration files ? *"
send "/usr/local/$package\r"
expect eof'

其中package是包含要安装的模块名称的变量。问题是,这个脚本不起作用并打印一条消息说:“无法读取文件”包的名称“:没有这样的文件或目录。

如何将变量传递给expect脚本?我不想创建一个单独的脚本,以期保持简单。

3 个答案:

答案 0 :(得分:1)

您的expect命令被单引号括起来。 shell内部的变量无法扩展。

试试这个:

expect "$package" -c "set timeout -1
set package [lindex $argv 0]
spawn sh install_pipeline
expect \"Where should I install the software packages ? *\"
send \"/usr/local/$package\r\"
expect \"Where should I install the pipeline calibration files ? *\"
send \"/usr/local/$package\r\"
expect eof"

或者,如果您想保留单引号:

expect "$package" -c 'set timeout -1
set package [lindex $argv 0]
spawn sh install_pipeline
expect "Where should I install the software packages ? *"
send "/usr/local/'"$package"'\r"
expect "Where should I install the pipeline calibration files ? *"
send "/usr/local/'"$package"'\r"
expect eof'

答案 1 :(得分:1)

根据Kenavoz的回答,我找到了解决方案。正如他所说,我的代码被简单的引号所包围,所以期望无法从主脚本中获取变量。因此,只使用正常引号将其解决问题,而无需将变量作为参数传递:

expect -c "set timeout -1
spawn sh install_pipeline
expect \"Where should I install the software packages ? *\"
send \"/usr/local/$package\r\"
expect \"Where should I install the pipeline calibration files ? *\"
send \"/usr/local/$package\r\"
expect eof"

答案 2 :(得分:0)

你可以通过环境传递它:

env pkg="$package" expect -c '
    set timeout -1
    spawn sh install_pipeline
    expect "Where should I install the software packages ? *"
    send "/usr/local/$env(pkg)\r"
    expect "Where should I install the pipeline calibration files ? *"
    send "/usr/local/$env(pkg)\r"
    expect eof
'