CRONTAB,何时设置路径变量

CRONTAB,何时设置路径变量

我有两个 bash 脚本,运行时它们都可以工作。

然而,当我尝试在 中运行它们时cron,一个脚本(Scipt 2)可以工作,而另一个脚本(Script 1)则不能。

我已将问题范围缩小到为非工作脚本(脚本 1)中使用的&命令设置PATH变量。finddate

我有点困惑,因为最初在 中工作的另一个脚本(脚本 2)cron也有find&date命令。

为什么会这样呢?

Linux 发行版:Ubuntu 服务器

脚本1(需要设置路径):

#!/bin/bash
#Delete Cam Folders Older Than 7 Days
PATH=/usr/bin:/bin <- MUST ADD THIS TO WORK PROPERLY IN CRON
file=$(find /cams -type d -mtime +5 | tr '\n' ' ')

if test -z "$file"
then
    echo "$(date "+%b %d %Y %T") : No directories older than 7 days"
else
    echo "$(date "+%b %d %Y %T") : Deleting Directies ${file}"
 #       find /cams -type d -mtime +7 -exec rm -rf {} +
fi

脚本2:

#!/bin/bash
file_date=$(date '+%A_%b-%d-%Y')
#mkdir /cams/$file_date

# record_hq.sh
# Record ip cam in segments
# Start of Day to Create Directory
# This will print the current date and time in a format appropriate for storage
STARTTIME=$(date '+%I%M%p')

## IP Camera Names ##
# Creating date stamps for each of the five cameras
CAM1D=/CAM01_$STARTTIME
#CAM2D=CAM2D_$STARTTIME
#CAM3D=CAM3D_$STARTTIME
#CAM4D=CAM4D_$STARTTIME
#CAM5D=CAM5D_$STARTTIME

## Network and Local Storage Locations  ##
HQDIR="/cams/"

## Record Time per File ##
HQLENGTH="3600" # (Runtime expressed in seconds)

## Record Settings ##
#
# -v 0    // Log level = 0
# -i      // Input url
# -vcodec // Set the video codec. This is an alias for "-codec:v".
# -an     // Disable audio recording
# -t      // Stop writing the output after its duration reaches duration
#

echo "$(date "+%b %d %Y %T") : (Hourly Recording) Started recording file                 ${CAM1D}.mkv"
if ffmpeg -v 24 -rtsp_transport tcp -i "rtsp://admin:[email protected]:554/h264Preview_01_main" -vcodec copy -an -t $HQLENGTH $HQDIR$file_date$CAM1D.mkv ; then
    echo "$(date "+%b %d %Y %T") : (Hourly Recording) Stoped recording file 
else
    echo "$(date "+%b %d %Y %T") : (Hourly Recording) Recording Script Failed"

答案1

Cron 不使用 .bashrc 路径。正常执行使用 .bashrc 路径。这就是您需要 PATH 变量的原因。

而且你的 PATH 变量看起来也不同。

看看系统范围的 cron 文件看起来像这样

This has the username field, as used by /etc/crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file.
# This file also has a username field, that none of the other crontabs 
do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user   command
42 6 * * *   root    run-parts --report /etc/cron.daily
47 6 * * 7   root    run-parts --report /etc/cron.weekly
52 6 1 * *   root    run-parts --report /etc/cron.monthly
01 01 * * 1-5 root python /path/to/file.py

答案2

现在,这两个脚本似乎都可以在不添加 PATH 命令的情况下运行。即使重新启动后。真的不确定发生了什么。我什至无法继续测试,所以我现在就回答我的问题。

相关内容