expect 交互时 管道符的问题

今天同事说expect交互出了问题,无法调用gzip解压导入数据库,但是手动执行却没问题
先来看看问题

#!/usr/bin/expect
set timeout 10000
spawn zcat db_xd_20220208_133003.sql.gz | mysql -u xd -p xd
expect -re ".*password"
send "xxxx\n"

expect eof

exit

执行后输出

spawn zcat db_xd_20220208_133003.sql.gz | mysql -u xd -p xd
gzip: invalid option -- 'u'
Try `gzip --help' for more information.
send: spawn id exp4 not open
    while executing
"send "xxxx\n""
    (file "./c.sh" line 7)

这里可以看到, 报出 gizp --u不存在的错误
进行排查

  1. 手动执行 zcat db_xd_20220208_133003.sql.gz | mysql -u xd -p xd 没问题成功导入

那么问题出在哪里? 为什么会报gzip --u的错误

  1. gzip --help查看 确实没有 u 的参数
  2. -u是写在 mysql 后面的 不应该是 zcat 的参数
  3. 很明显 管道符 | 并没有生效
  4. 手工操作可以成功,那么说明expect下的管道符|并未生效

好了 有了原因那么就开始找方案, 找到了这个
https://unix.stackexchange.com/questions/448053/expect-command-pipes-and-gzip

expext中要处理管道符 需要使用 sh -c { shell }的模式

修改脚本即可

#!/usr/bin/expect
set timeout 10000
spawn sh -c {zcat db_xd_20220208_133003.sql.gz | mysql -u xd -p xd}
expect -re ".*password"
send "xxxx\n"

expect eof

exit
posted @ 2022-02-09 09:55  Z_DK  阅读(166)  评论(0编辑  收藏  举报