在 cron 中备份 postgres 数据库的问题

issues backing up postgres databases in cron

我正在尝试备份 postgres 数据库。为此,我正在 运行 执行 cron 作业。问题是 postgres 运行s 在用户 postgres 下,我认为我不能在 ubuntu 用户下 运行 一个 cron 作业。我试图在 postgres 用户下创建一个 cron 作业,但也没有用。我的脚本,如果以 postgres 用户身份登录就可以正常工作。 这是我的脚本

#!/bin/bash
# Location to place backups.
backup_dir="/home/postgres-backup/"
#String to append to the name of the backup files
backup_date=`date +%d-%m-%Y`
#Numbers of days you want to keep copie of your databases
number_of_days=30
databases=`psql -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'`
for i in $databases; do
  if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then
    echo Dumping $i to $backup_dir$i\_$backup_date
    pg_dump -Fc $i > $backup_dir$i\_$backup_date
  fi
done
find $backup_dir -type f -prune -mtime +$number_of_days -exec rm -f {} \;

如果我这样做

sudo su - postgres

明白了

-rwx--x--x 1 postgres postgres  570 Jan 12 20:48 backup_all_db.sh

当我这样做时

./backup_all_db.sh

它在 /home/postgres-backup/

中备份

然而,无论我是在 postgres 下还是在 ubuntu.

下添加 cron 作业,它都无法正常工作

这是我的 cronjob

0,30 * * * * /var/lib/pgsql/backup_all_db.sh 1> /dev/null 2> /home/cron.err

感谢任何帮助

允许用户运行 cron 作业

如果 /etc/cron.allow 文件存在,则必须在其中列出用户才能允许 运行 crontab 命令。如果 /etc/cron.allow 文件不存在但 /etc/cron.deny 文件存在,则用户不得在 /etc/cron.deny 文件中列出以便 运行 crontab。

在两个文件都不存在的情况下,当前 Ubuntu(和 Debian,但不是其他一些 Linux 和 UNIX 系统)的默认设置是允许所有用户 运行使用 crontab 的工作。

添加 cron 作业

使用此命令为当前用户添加一个 cron 作业:

crontab -e

使用此命令为指定用户添加 cron 作业(需要权限):

crontab -u <user> -e

补充阅读

man 5 crontab

Ubuntu 中的 Crontab:https://help.ubuntu.com/community/CronHowto