我试图编写一个bash脚本来在Debian 6 VPS上安装PostgreSQL服务器。 我一直擦拭服务器,我想写一些东西来自动安装它。
#!/bin/bash export PATH=/bin:/usr/bin:/sbin:/usr/sbin function print_info { echo -n -e '\e[1;36m' echo -n $1 echo -e '\e[0m' } function print_warn { echo -n -e '\e[1;33m' echo -n $1 echo -e '\e[0m' } function check_install { if [ -z "`which "$1" 2>/dev/null`" ] then executable=$1 shift while [ -n "$1" ] do DEBIAN_FRONTEND=noninteractive apt-get -q -y install "$1" print_info "$1 installed for $executable" shift done else print_warn "$2 already installed" fi } check_install postgresql postgresql sudo -u postgres psql -c"ALTER user postgres WITH PASSWORD '$1'" sudo service postgresql restart
但是,这不能成功运行。
root@server:~# bash -x ./pgsql.sh password + export PATH=/bin:/usr/bin:/sbin:/usr/sbin + PATH=/bin:/usr/bin:/sbin:/usr/sbin + check_install postgresql postgresql ++ which postgresql + '[' -z '' ']' + executable=postgresql + shift + '[' -n postgresql ']' + DEBIAN_FRONTEND=noninteractive + apt-get -q -y install postgresql Reading package lists... Building dependency tree... Reading state information... postgresql is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 7 not upgraded. + print_info 'postgresql installed for postgresql' + echo -n -e '\e[1;36m' + echo -n postgresql installed for postgresql postgresql installed for postgresql+ echo -e '\e[0m' + shift + '[' -n '' ']' + sudo service postgresql start + sudo -u postgres psql '-cALTER user postgres WITH PASSWORD '\''password'\''' perl: warning: Setting locale failed. perl: warning: Falling back to the standard locale ("C"). could not change directory to "/root" psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? + sudo service postgresql restart
你的脚本工作正常。 我只是在干净的debian wheezy上执行它,它工作正常。 所以问题不是你的脚本,而是你的SQL数据库没有运行,所以你不能做任何查询。
psql: could not connect to server: No such file or directory
关于“没有这样的文件”的错误是因为你正在根目录sudoing到用户没有权限在那里。 root@debian:~# sudo -u postgres ls ls: cannot open directory .: Permission denied root@debian:~# sudo -u postgres pwd /root
编写脚本是很好的,但是你需要把服务器当作牛而不是宠物。 用密码安装postgresql是一个状态,因为脚本可能由于各种原因失败,所以不能被视为可靠的。 当您安装任何自动化工具时,您可以轻松configuration服务器,并确保结果(服务器状态)将(几乎)始终如您所愿。
例如木偶会用postgres模块做这个工作:
class { 'postgresql::server': postgres_password => 'password' }
错误消息是说它无法连接到服务器; 因为你没有安装任何东西(在输出中,postgres已经安装),它不会validation它已经成功启动。
您可能需要添加以下内容:
check_install postgresql postgresql sudo service postgresql start sudo -u postgres psql -c"ALTER user postgres WITH PASSWORD '$1'" sudo service postgresql restart
正如汤姆·肖(Tom Shaw)在他的评论中提到的那样,你可以在脚本中添加set -x到你的脚本,让它在你的脚本运行之前输出你的每一行脚本,这样你就可以看到它到底在做什么。 此外,如果遇到非零值,可以使用set -e使其退出,这可能有助于未来; 即,如果postgres安装失败,尝试重新启动它是没有意义的。