Crontab 未运行脚本

Crontab 未运行脚本

我已设置 crontab 来运行 2 个脚本:

$ crontab -l
0 20 * * * /usr/bin/bkp.sh --silent > /home/perforce/logs/bkp.log 2>&1
0 21 * * * /usr/bin/flsbk.sh --silent > /home/perforce/logs/flsbk.log 2>&1 

第一个脚本没有运行。

我设置了crontab -esudo crontab -e

我遇到的错误是这样的。来自/home/perforce/output.log

====================================================================================

Starting Backup

====================================================================================

Output location:  /home/perforce/output.log

Running p4 verify...
/usr/bin/bkp.sh: line 22: p4: command not found
Done! (No error)

Running p4 admin checkpoint...
/usr/bin/bkp.sh: line 46: p4: command not found
Done!
/usr/bin/bkp.sh: line 51: p4: command not found
 (Error)

我的脚本是这样的:

#!/bin/bash

echo
echo "===================================================================================="
echo "Starting Backup"
echo "===================================================================================="

# Defines output folder and log name
OUTPUT_FOLDER='/home/perforce/'
OUTPUT_FILE='output.log'

OUTPUT=$OUTPUT_FOLDER$OUTPUT_FILE

echo "Output location: " $OUTPUT

# Creates a temp file
TMPFILE=`mktemp`

echo -n "Running p4 verify..."

# Run the p4 and send the output to the temp file
p4 verify -q //... > $TMPFILE

echo -n " Done!"

# Check if it's empty (no error)

# Copy the content to another variable, so we don't mess up with the original output
RESULT=`cat $TMPFILE`

if [ "$RESULT" != "" ];
then
  echo " (Error, saving to log)"

  # Save error on output file
  `echo $RESULT > $OUTPUT`

  exit
fi

echo " (No error)"

echo -n "Running p4 admin checkpoint..."

# Run the p4 and send the output to the temp file
p4 admin checkpoint > $TMPFILE

echo -n "Done!"

# The file created by the last command
COUNTER=`p4 counter journal`

FILE=/perforce_depot/checkpoint.$COUNTER

# Check if the file was created
if [ -f "$FILE" ]
then
  echo " (No error)"
else
  echo " (Error)"
  exit
fi

echo  -n "Backing up ..."

# Finaly, let's create the backup
#`cp -r /perforce_depot  '/media/perforce/Seagate Backup Plus Drive/perforcebk'`
START=$(date +%D)

FOLDER_NAME=`echo $START | tr -s '/' | tr '/' '_'`
FOLDER_PATH='/media/perforce/BackupDrive/perforcebk'
BACKUP_PATH=$FOLDER_PATH/bkp_$FOLDER_NAME

mkdir -p $BACKUP_PATH

cp -r /perforce_depot $BACKUP_PATH

echo " Done!"

p4位于/usr/local/bin

有人知道我为什么会收到这个错误吗?如果我通过 ssh 连接到机器并手动运行,sh bhp.sh它运行起来不会出现问题,也不会出现任何错误。

答案1

Cron 脚本不会在您的“正常”环境中运行。输出明确指出:

 /usr/bin/bkp.sh: line 22: p4: command not found

你说:

p4位于/usr/local/bin

这可能意味着$PATH不包括/usr/local/bin,仅此而已。因此,修改您的 cron 脚本并在 shebang 后添加以下内容:

#!/bin/bash

set -e
PATH="/usr/local/bin:$PATH"

注意:set -e如果某些命令失败,将导致脚本退出。它不是解决特定问题的必需步骤,但将来可能会解决很多麻烦。请考虑在所有脚本中使用它。

相关内容