将变量与数字进行比较

时间:2018-05-14 13:29:14

标签: linux bash shell

以下代码抛出错误,我不知道为什么会发生错误。

#! /bin/bash

# This script checks if your Apache log is older than two weeks.
# If so, the files will be deleted

# Defining savepath
savePath="/var/log/test.log"

# Startup
printf "\n*** Starting logrotate at $(date +'%m-%d-%y %H:%M:%S') ***" >> $savePath

# Check if Apache logs older than two weeks are existing
apacheCount=`sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l`

# If so, delete 'em!
if [ "$apacheCount" != "0" ]; then

    sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +8 -exec rm -f {} \;
    newValue=sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l

    if [ "$newValue" == "0" ]; then
            printf "\n$(date +'%m-%d-%y %H:%M:%S'): $apacheCount Apache Log(s) has / have been deleted." >> $savePath
    else
            printf "\n$(date +'%m-%d-%y %H:%M:%S'): There was an error. $(($apacheCount-$newValue)) items were not deleted." >> $savePath
    fi
else
    printf "\n$(date +'%m-%d-%y %H:%M:%S'): No Apache Log older than two weeks found." >> $savePath
fi

执行程序时会抛出以下错误:

  

[:意外的操作员

     

算术表达式:期待主要:" 1 - "

我对bash比较陌生,所以如果你能解释我哪里出错了,我会很感激。

2 个答案:

答案 0 :(得分:0)

下面的行有一个错误,``添加

newValue=`sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l`

改进代码:

#! /bin/bash

# This script checks if your Apache log is older than two weeks.
# If so, the files will be deleted

# Defining savepath
savePath="/var/log/test.log"

# Startup
printf "\n*** Starting logrotate at $(date +'%m-%d-%y %H:%M:%S') ***" >> $savePath

# Check if Apache logs older than two weeks are existing
apacheCount=`sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l`

# If so, delete 'em!
if [ "$apacheCount" != "0" ]; then

   sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +8 -exec rm -f {} \;
   #the line below had an error, `` added
   newValue=`sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l`

   if [ "$newValue" == "0" ]; then
        printf "\n$(date +'%m-%d-%y %H:%M:%S'): $apacheCount Apache Log(s) has / have been deleted." >> $savePath
   else
        printf "\n$(date +'%m-%d-%y %H:%M:%S'): There was an error. $(($apacheCount-$newValue)) items were not deleted." >> $savePath
   fi
else
   printf "\n$(date +'%m-%d-%y %H:%M:%S'): No Apache Log older than two weeks found." >> $savePath
fi

答案 1 :(得分:0)

您好在脚本中错误地捕获newValue中的值。修改代码中的两行以解决问题: -

#better use below syntax
apacheCount=$(sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l)


newValue=$(sudo /usr/bin/find /var/log/apache2/ -iname "access.log.*.gz" -mtime +15 | wc -l)
相关问题