温馨提示×

Ubuntu expect如何与Shell脚本配合

小樊
100
2024-07-17 14:31:46
栏目: 编程语言

在Ubuntu中,您可以使用expect命令与Shell脚本配合来自动化交互式任务。以下是一个简单的示例:

  1. 首先安装expect工具:在终端中运行以下命令:
sudo apt-get install expect
  1. 创建一个Shell脚本(例如test.sh),内容如下:
#!/bin/bash

# Shell脚本中的交互式命令
read -p "Enter your name: " name
echo "Hello, $name!"
  1. 创建一个expect脚本(例如test.exp),内容如下:
#!/usr/bin/expect

spawn ./test.sh
expect "Enter your name: "
send "Alice\r"
expect eof

在这个示例中,expect脚本会自动执行Shell脚本test.sh,并模拟用户输入"Alice"作为名字,然后等待Shell脚本执行完毕。

  1. 在终端中运行expect脚本:
chmod +x test.sh
chmod +x test.exp
./test.exp

这样,您就可以使用expect命令与Shell脚本配合来完成自动化交互式任务。您可以根据实际需求修改expect脚本中的expect和send语句来模拟不同的用户输入。

0