首页 > 技术文章 > expect小工具,在postgresql中执行sql的shell脚本

jiaoyiping 2017-09-25 23:21 原文

脚本内容:

#!/usr/bin/expect
set database [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set command  [lindex $argv 3]
spawn  psql -U $username -d $database -c "$command"  -W
expect "Password: "
send "$password\n"
expect eof

postgresql 默认的命令行是需要交互的,并不能实现在crontab中自动执行一个sql语句之类的操作,借助expect就可以实现这个功能(如果没有except,需要先安装expect)

使用方法(假设将上边的脚本保存为runcommand.sh):

./runcommand.sh dbname username password command

推荐阅读