如何使bash脚本正确嵌套?

时间:2015-08-09 07:28:33

标签: bash shell expect heredoc quoting

这是期望文件,可以成功运行。

#!/usr/bin/expect  -f
set host vps_ip
set user test
set loginpwd  passwd
set adminpwd  passwd
set timeout 300
set prompt "#|>|\\\$"    
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
expect -nocase  "password:"
send "$loginpwd\r"
expect eof
spawn  ssh  $user@$host
expect -nocase "password:"
send "$loginpwd\r"
expect -re $prompt
send "su\r"
expect  "assword:"
send "$adminpwd\r"
expect -re $prompt
send "mysql -u root -pxxxx wpdatabase < /tmp/wpdatabase_backup.sql\r"
expect eof

这是bash文件:

mysqlword="xxxx"
mysqldump -u root -p$mysqlword wpdatabase > /home/wpdatabase_backup.sql

现在我想将expect文件嵌套在bash文件中,因为bash文件比期望文件更复杂,bash文件中的大多数行都被省略了。

代码:

#!/usr/bin/bash
mysqlword="xxxx"
mysqldump -u root -p$mysqlword wpdatabase > /home/wpdatabase_backup.sql    
/usr/bin/expect <<EOD
set host vps_ip
set user test
set loginpwd  passwd
set adminpwd  passwd
set timeout 300
set prompt "#|>|\\\$"

spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
expect -nocase  "password:"
send "$loginpwd\r"
expect eof
spawn  ssh  $user@$host
expect -nocase "password:"
send "$loginpwd\r"
expect -re $prompt
send "su\r"
expect  "assword:"
send "$adminpwd\r"
expect -re $prompt
send "mysql -u root -pxxxx wpdatabase < /tmp/wpdatabase_backup.sql\r"
expect eof
<<EOD

发生错误: spawn scp /home/wpdatabase_backup.sql @:/ tmp
ssh:无法解析主机名:未知的名称或服务
失去联系
发送:spawn id exp6未打开
    执行时 “发送”\ r“”

引用终结者:

cat<<'EOD'
set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
EOD

结果:

set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp

但是如何使结果的输出在bash中运行?

/usr/bin/expect  <<cat<<'EOD'
set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
EOD

代码无法运行!

1 个答案:

答案 0 :(得分:0)

这是因为在here-document中有一个不带引号的终结符,如EOD,参数替换由shell执行。如果您将/usr/bin/expect替换为cat

,则可以看到
$ cat<<EOD
set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
EOD

结果:

set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   @:/tmp

那么,如何避免参数替换?引用终结者:

$ cat<<'EOD'
set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp
EOD

结果:

set host vps_ip
set user test
spawn scp  /home/wpdatabase_backup.sql   $user@$host:/tmp