Bash 脚本不在 CRON 中执行(可能与 Sudo 命令有关?)

Bash script does not execute in CRON (might be to do with Sudo commands?)

我有一个 bash 脚本,它使用 ssh 隧道远程获取 PSQL 转储,然后将转储放入本地 MySQL 数据库。

我似乎无法让 CRON 运行 它。

我执行了以下步骤:

1) 运行:

sudo crontab -e

2) 输入以下内容让脚本每10分钟执行一次。脚本也需要大约 2-3 分钟才能完全执行。

*/10 * * * * /home/ubuntu/psqlimport 2>&1 /home/ubuntu/cronlog.log

3) 运行:

sudo chmod +x /home/ubuntu/psqlimport

4) 重新启动 CRON:

sudo /etc/init.d/cron restart

我检查了我的数据库以查看是否有任何更新并且有 none,就好像脚本从未执行过一样。也没有创建 /home/ubuntu/cronlog.log 文件。当我 运行:

bash psqlimport

脚本按预期执行。

为什么 CRON 作业不执行脚本?

文件名:psqlimport

#!bin/bash

###
#
# PostgreSQL to MySQL Dump  program
#
# Filename: psqlimport
# Description: This program dumps the 3 tables from a
# remote PostgreSQL database, converts the dump file
# into MySQL translatable INSERT INTO queries,
# and inputs the data into the local
#  MySQL Inbevdash6 database.
#
# Script can be copied to the
# /etc/cron.daily folder for daily database updates.
#
#
# Script written by ramabrahma@Whosebug
# Date: December 15, 2015
# Version: 01
#


#Set the dump file and temp file
DUMPFILE='psql.dump.sql' || (echo "assign var failed" 1>&2; exit 1)
TMPFILE=`mktemp` || (echo "mktemp failed" 1>&2; exit 1)

#Tables to dump: table1, table2, table3
#Dump as INSERT queries statements


sudo -E sshpass -p "<remote host password>" \
ssh username@remote_host \
pg_dump -U database_username -t table1 \
 -t table2 -t table3 \
 --column-inserts --data-only psqldatabase \
 | awk '/^INSERT/ {i=1} /^SELECT/ {i=0} i' \
 > "$TMPFILE" \
 || (echo "pg_dump failed" 1>&2; exit 1)


#Adding transaction blocks to the dump file
(echo "start transaction; truncate table table1; "; \
echo "truncate table table2; "; \
echo "truncate table table3; "; \
cat "$TMPFILE"; echo 'commit;' ) \
 > "$DUMPFILE" \
 || (echo "parsing dump file failed" 1>&2; exit 1)

#Inputting the dump file to the MySQL database
mysql --defaults-file="/home/ubuntu/.mysql.db.cfg" < "$DUMPFILE" \
  || (echo "mysql failed" 1>&2; exit 1)

#Remove the temp file created
rm "$TMPFILE"
rm "$DUMPFILE"

您的shebang有误:

#!bin/bash

应该是

#!/bin/bash

bin/bash 可能不是通向任何东西的路径,除非你在 / 之外执行。当您手动执行脚本时,这不是问题,因为 bash psqlimport 显式调用 bash 来评估脚本。如果您尝试 运行 ./psqlimport 到 运行 脚本,您将能够看到实际问题。