Cronjob脚本没有按预期工作

时间:2016-05-11 22:38:18

标签: linux bash unix cron selinux

我有一个脚本,当我自己手动运行它时可以正常工作,但似乎无法从crontab正常运行。

主要错误是没有设置(外部)环境变量。

我在cronjob定义上方添加了SHELL=/bin/bash,但仍然遇到了相同的错误。

我在下面复制并粘贴的脚本。干杯求助

#!/bin/bash
# export MYSQL_PORT_3306_TCP_ADDR=`awk 'NR==1 {print $1}' /etc/hosts`

set -e

MOUNT=/mnt/s3b/
BACKUP=/root/backups
mkdir -p $BACKUP
NOW=$(date +"%Y-%m-%d-%H%M")
DB_FILE="$MYSQL_ENV_MYSQL_DATABASE.$NOW.sql"

/usr/bin/s3fs <bucket_name> $MOUNT -ouse_cache=/tmp -odefault_acl=public-read -ononempty

mysqldump -h$MYSQL_PORT_3306_TCP_ADDR -uroot -p$MYSQL_ENV_MYSQL_ROOT_PASSWORD $MYSQL_ENV_MYSQL_DATABASE > /tmp/$DB_FILE

tar -czvf $BACKUP/"$DB_FILE.tar.gz" -P /tmp/$DB_FILE

cp $BACKUP/"$DB_FILE.tar.gz" $MOUNT/data/

如下所示,所有环境变量返回错误:

 May 11 00:17:59 fcf074b9e5ee kernel: [293368.874868] SELinux: mount invalid.    Same superblock, different security settings for (dev mqueue, type mqueue)
 May 11 00:18:14 fcf074b9e5ee kernel: [293383.903080] docker0: port 6(veth2f6467f) entered forwarding state
 May 11 01:29:26 fcf074b9e5ee s3fs[78]: s3fs.cpp:s3fs_init(3334): init v1.79(commit:unknown) with OpenSSL
 May 11 01:29:26 fcf074b9e5ee s3fs[78]: s3fs.cpp:s3fs_check_service(3729):     Could not connect wrong region us-east-1, so retry to connect region eu-west-1.
 May 11 01:31:10 fcf074b9e5ee s3fs[93]: s3fs.cpp:s3fs_init(3334): init v1.79(commit:unknown) with OpenSSL
 May 11 01:31:10 fcf074b9e5ee s3fs[93]: s3fs.cpp:s3fs_check_service(3729): Could not connect wrong region us-east-1, so retry to connect region eu-west-1.
  May 11 10:25:02 fcf074b9e5ee kernel: [329791.913331] hrtimer: interrupt took 2331455 ns

  mysqldump -h -uroot -p > /tmp/.2016-05-11-0015.sql

1 个答案:

答案 0 :(得分:1)

正如@ that-other-guy指出的那样,环境变量$ MYSQL_ENV_MYSQL_DATABASE,$ MYSQL_ENV_MYSQL_ROOT_PASSWORD未设置。

当进程分叉时,环境变量从进程继承到子进程。这意味着crontab作业将从crontab服务继承环境。安装crontab作业时在shell中设置的环境变量将不会被保留。

您应该添加shell脚本:

MYSQL_ENV_MYSQL_DATABASE="mydatabase"
MYSQL_ENV_MYSQL_ROOT_PASSWORD="mypassword"