gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:26:30 27 4
gpt4 key购买 nike

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

最佳答案

您的 shebang 中有错误:

#!bin/bash

应该是

#!/bin/bash

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

关于mysql - Bash 脚本不在 CRON 中执行(可能与 Sudo 命令有关?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com