检查文件是否存在且不为空

Gom*_*mar 2 scheduling files

我想xx_x__x.log在每周日凌晨 2:30检查该位置是否存在文件或文件大小为 0。我有一个脚本来检查文件大小并检查它是否存在,但我不知道如何在特定时间检查。

the*_*fog 14

从 man bash | less '+/^\s*CONDITIONAL'

-s file
如果文件存在且大小大于零,则为真。

要让脚本在预定义的时间运行,请将您的代码放入可执行的 scipt 并将其加载到 cronjob 中。

我怀疑您可能可以将您的命令放入单衬纸中并将其装入 crobtab 中?(我很想知道是否有其他人成功地做到了这一点)
但是 cron 命令的问题在于

  1. 它们没有连接到终端 - 我知道{虽然你可能会检查lsof或其他东西} - 所以当你建立你的 cron 命令时,你不会得到任何关于出错的调试输出/反馈
  2. 您必须等待一段时间才能测试您的 cron 命令

出于这些原因,我建议只将您的命令放入可执行脚本中,以便您可以在编码器友好的环境中编写代码 - 即终端,然后当您感到满意时,它的行为是正确的,然后加载一个命令以将其调用到定时任务表

所以说这是你的剧本 /tmp/checksize.sh

#!/bin/bash

if [[ -s /tmp/xx_x__x.log  ]]
then 
        printf "\n\n%s\n\n\n" true > /tmp/sizelog.log
else 
        printf "\n\n%s\n\n\n" false > /tmp/sizelog.log
fi
Run Code Online (Sandbox Code Playgroud)

只需运行crontab -e并添加命令

5 0 * * * /tmp/checksize.sh
Run Code Online (Sandbox Code Playgroud)

这意味着:#每天午夜后五分钟运行

关于正确把握时机

从 man 5 crontab

Commands  are  executed by cron(8) when the minute, hour, and month of
       year fields match the current time, and when at least one  of  the  two
       day  fields  (day of month, or day of week) match the current time (see
       ``Note'' below).  cron(8) examines cron entries once every minute.  The
       time and date fields are:

          field      allowed values
          -----      --------------
          minute         0-59
          hour       0-23
          day of month   1-31
          month      1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sun, or use names)

[...]

EXAMPLE CRON FILE
       The following lists an example of a user crontab file.

       # use /bin/bash to run commands, instead of the default /bin/sh
       SHELL=/bin/bash
       # mail any output to `paul', no matter whose crontab this is
       MAILTO=paul
       #
       # run five minutes after midnight, every day
       5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
       # run at 2:15pm on the first of every month -- output mailed to paul
       15 14 1 * *     $HOME/bin/monthly
       # run at 10 pm on weekdays, annoy Joe
       0 22 * * 1-5    mail -s "It's 10pm" joe%Joe,%%Where are your kids?%
       23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
       5 4 * * sun     echo "run at 5 after 4 every sunday"
       # Run on every second Saturday of the month
       0 4 8-14 * *    test $(date +\%u) -eq 6 && echo "2nd Saturday"
Run Code Online (Sandbox Code Playgroud)


小智 2

要检查文件是否存在于某个位置,您可以-f在if语句中使用测试。

if [ -f "$FILE" ]; then
Run Code Online (Sandbox Code Playgroud)

(正如 the_velour_fog 所说,即使文件为空,表达式也会返回 True)

  • 您可以使用“[[ -s $FILE ]]”,如果文件存在但为空,它将返回“1”(假) (8认同)
  • `[ $FILE -f ]` 即使文件为空,这也会返回 true (2认同)