【问题标题】:Bash script does not execute in CRON (might be to do with Sudo commands?)Bash 脚本不在 CRON 中执行(可能与 Sudo 命令有关?)
【发布时间】:2016-03-25 14:04:38
【问题描述】:

我有一个 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

我检查我的数据库以查看是否有任何更新并且没有,就好像脚本从未执行过一样。也没有创建 /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@stackoverflow
# 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"

【问题讨论】:

    标签: mysql bash ubuntu cron pg-dump


    【解决方案1】:

    您的shebang 中有错误:

    #!bin/bash
    

    应该是

    #!/bin/bash
    

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

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 2018-05-20
      • 2017-01-06
      • 2017-01-04
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      相关资源
      最近更新 更多