shell脚本中 怎么写才能执行shell执行中需要交互输入回车,Yes/NO Y/N
时间: 2024-01-23 09:02:15 浏览: 208
要在Shell脚本中实现需要交互输入的操作,可以使用`expect`命令来模拟用户交互。下面是一个示例脚本,用于自动化执行MySQL安全配置时需要交互的操作:
```shell
#!/usr/bin/expect -f
# 设置变量
set timeout 60
set password [lindex $argv 0]
# 连接MySQL并进行安全配置
spawn mysql_secure_installation
# 匹配并回答安全配置问题
expect "Enter current password for root (enter for none):"
send "\r"
expect "Set root password?"
send "Y\r"
expect "New password:"
send "$password\r"
expect "Re-enter new password:"
send "$password\r"
expect "Remove anonymous users?"
send "Y\r"
expect "Disallow root login remotely?"
send "Y\r"
expect "Remove test database and access to it?"
send "Y\r"
expect "Reload privilege tables now?"
send "Y\r"
expect eof
```
这个脚本使用`expect`命令来模拟与MySQL安全配置交互的过程。您可以将此脚本保存为`mysql_secure_installation.sh`并使用以下命令运行它:
```shell
chmod +x mysql_secure_installation.sh
./mysql_secure_installation.sh your_mysql_password
```
请注意,`your_mysql_password`应替换为您要设置的实际MySQL密码。
阅读全文