我是shell脚本的新手.我编写了一个shell脚本来对MysqL数据库进行增量备份.脚本采用可执行格式,在手动执行时运行成功,但在通过crontab执行时失败.
Crontab条目是这样的:
*/1 * * * * /home/db-backup/MysqLbackup.sh
下面是shell脚本代码 –
#!/bin/sh MyUSER="root" # USERNAME MyPASS="password" # PASSWORD MyHOST="localhost" # Hostname Password="" #Linux Password MysqL="$(which MysqL)" if [ -z "$MysqL" ]; then echo "Error: MysqL not found" exit 1 fi MysqLADMIN="$(which MysqLadmin)" if [ -z "$MysqLADMIN" ]; then echo "Error: MysqLADMIN not found" exit 1 fi CHOWN="$(which chown)" if [ -z "$CHOWN" ]; then echo "Error: CHOWN not found" exit 1 fi CHMOD="$(which chmod)" if [ -z "$CHMOD" ]; then echo "Error: CHMOD not found" exit 1 fi GZIP="$(which gzip)" if [ -z "$GZIP" ]; then echo "Error: GZIP not found" exit 1 fi CP="$(which cp)" if [ -z "$CP" ]; then echo "Error: CP not found" exit 1 fi MV="$(which mv)" if [ -z "$MV" ]; then echo "Error: MV not found" exit 1 fi RM="$(which rm)" if [ -z "$RM" ]; then echo "Error: RM not found" exit 1 fi RSYNC="$(which rsync)" if [ -z "$RSYNC" ]; then echo "Error: RSYNC not found" exit 1 fi MysqLBINLOG="$(which MysqLbinlog)" if [ -z "$MysqLBINLOG" ]; then echo "Error: MysqLBINLOG not found" exit 1 fi # Get data in dd-mm-yyyy format NOW="$(date +"%d-%m-%Y-%T")" DEST="/home/db-backup" mkdir $DEST/Increment_backup.$NOW LATEST=$DEST/Increment_backup.$NOW $MysqLADMIN -u$MyUSER -p$MyPASS flush-logs newestlog=`ls -d /usr/local/MysqL/data/MysqL-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1` echo $newestlog for file in `ls /usr/local/MysqL/data/MysqL-bin.??????` do if [ "/usr/local/MysqL/data/MysqL-bin.$newestlog" != "$file" ]; then echo $file $CP "$file" $LATEST fi done for file1 in `ls $LATEST/MysqL-bin.??????` do $MysqLBINLOG $file1>$file1.$NOW.sql $GZIP -9 "$file1.$NOW.sql" $RM "$file1" done $RSYNC -avz $LATEST /home/rsync-back
>首先,当在crontab上安排时,它没有显示任何错误.我怎样才能知道脚本是否正在运行?
>其次,在crontab中执行shell脚本的正确方法是什么.
一些博客建议改变环境变量.什么是最好的解决方案
当我回复PATH时,我得到了这个
/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/MysqL/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin
问题可能是您的$PATH在手动环境中与crontab运行时的不同.因此,找不到您的可执行文件.要解决此问题,请首先在手动环境中打印路径(echo $PATH),然后在crontab中运行的脚本顶部手动设置PATH.或者只是按照完整路径参考程序.
export PATH="/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/MysqL/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin"