我试图编写一个简单的脚本来确定文件夹中是否存在新文件。最终它将与另一个脚本结合在一起,该脚本将创建一堆文件,然后删除一些不符合某些条件的文件,并告诉您以后是否有符合该条件的新文件。
出于测试目的,我创建了一个名为booty的文件夹,并在其中放置了1个文件。
然后我写了这个bash脚本:
#! /bin/bash
declare -i prev=$(ls booty/ | wc -l)
echo 'we have '$prev' files'
echo '--------------------------------'
echo 'testing a 1 > 1'
if [ $now > 1 ]; then
echo 'we have a new file: WRONG'
else
echo ' no new files: GREAT!'
fi
echo '--------------------------------'
echo 'lets ad a file'
touch booty/new.txt
declare -i now=$(ls booty/ | wc -l)
echo 'now we have '$now' files'
echo 'was ' $prev ' and now ' $now 'files'
if [ $now > $prev ]; then
echo 'we have a new file: GREAT!'
else
echo ' No new files WRONG'
fi
echo '--------------------------------'
echo 'setting a static number for compare'
declare -i static=1
echo 'static set to ' $static
echo 'comparing static:'$static ' to prev:'$prev
if [ $static > $prev ]; then
echo 'static is greater than prev WRONG'
else
echo ' static NOT greater than prev GREAT!'
fi
echo '---------------------------------'
echo 'lets try an incriment of static'
static=$(expr $static + 1)
echo 'now static now set to ' $static
if [ $static > $prev ]; then
echo 'static is greater than prev GREAT!'
else
echo ' NOT greater prev WRONG'
fi
rm booty/new.txt
我期待所有的“胜利!”可以打印出来,但是当我得到静态数时,我得到的是错误的结果..它回显了正确的值,但是当它比较1> 1时,它返回为真吗?参见下面的输出:
erilidde$ sh test.sh
we have 1 files
--------------------------------
testing a 1 > 1
no new files: GREAT!
--------------------------------
lets ad a file
now we have 2 files
was 1 and now 2 files
we have a new file: GREAT!
--------------------------------
setting a static number for compare
static set to 1
comparing static:1 to prev:1
static is greater than prev WRONG
---------------------------------
lets try an incriment of static
now static now set to 2
static is greater than prev GREAT!
我是bash脚本的新手,并认为这与数据类型有关,但是我迷路了。请告诉我我正在犯什么愚蠢的错误。
答案 0 :(得分:1)
您没有正确使用>,<,<=,> =运算符,请注意,在bash中,仅((... ...))构造允许算术扩展和求值(Double-Parentheses Construct)。对于方括号,您需要使用-gt,-eq,-lt ..条件(bash Comparison Operators)
在脚本顶部,我建议您在if语句中使用$ now之前将其声明为空变量