我如何“来源”期望脚本

Jaa*_*kko 1 shell shell-script environment-variables expect

我被迫使用如下脚本:

# test.sh
function my_fun
{
    echo "Give value for FOO"
    local my_var
    read my_var
    export FOO=$my_var
}

# Call my_fun function
my_fun
Run Code Online (Sandbox Code Playgroud)

通过从我的外壳采购它。

$ source test.sh
Give value for FOO
stackexchange
$ echo $FOO
stackexchange
Run Code Online (Sandbox Code Playgroud)

我想用expect自动化脚本,如下所示:

$ expect test.exp
$ echo $FOO
stackexchange
Run Code Online (Sandbox Code Playgroud)

中环境变量的数量和名称test.sh未知。

更新:

  • 将 my_fun 函数全部添加到 test.sh。

gle*_*man 6

根本问题是子进程不能改变其父进程的环境。这就是您需要source该 shell 脚本的原因,因此环境变量将保留在您当前的 shell 中。

Expect 是为spawn子进程设计的。您当前的 shell不会受到expect test.exp.

但是,您可以生成一个 shell,获取该 shell 脚本的源代码,然后通过与它交互来保持该shell 的存在:这不在我的脑海中并且未经测试:

#!/usr/bin/expect -f
set timeout -1
spawn $env(SHELL)
set myprompt "some pattern that matches your prompt"
expect -re $myprompt
send "source test.sh\r"
expect {
    "Give value for " {
        # provide the same answer for every question:
        send "some value\r"
        exp_continue
    }
    -re $myprompt
}
interact
Run Code Online (Sandbox Code Playgroud)

现在您正在与您生成的外壳进行交互。当你使用exit那个 shell 时,生成的 shell 死了,然后期望脚本结束,你又回到了当前的 shell(没有你初始化的变量)。