主要问题是我尝试解析ls以模拟“比较目录”,但是当我这样做时,由于使用嵌套的fors,因此无法正确比较其结果,因为两个文件名/字符串的比较即使它们一样,总是返回false
我尝试删除白色字符,但没有结果。
var1=$(ls -l $1 | grep -v ^d | tail -n +2 | tr -s " "| cut -d " " -f 9)
var2=$(ls -l $2 | grep -v ^d | tail -n +2 | tr -s " "| cut -d " " -f 9)
for i in $var1 ; do
i=$(printf "$i" | tr -d '[:space:]')
flag=0
var3=$(ls -l $1 | grep -v ^d | tail -n +2 | tr -s " " | grep $i | cut -d " " -f 5)
for j in $var2 ; do
j=$(printf $j | tr -d '[:space:]')
var4=$(ls -l $2 | grep -v ^d | tail -n +2 | tr -s " " | grep $j | cut -d " " -f 5)
if [ "$i" == "$j" ] ; then
if [ "$var3" != "$var4" ] ; then
flag=1
fi
else
flag=1
fi
done
if [ $flag -eq 1 ] ; then
printf "$i file does not exist on the $2 catalog\n"
printf "It 's size is :$var3 \n"
let Sum=$Sum+$var3
fi
done
答案 0 :(得分:4)
这不是字符串比较问题,而是逻辑问题。
我写给您a MCVE的代码更少,依赖更少的情况也证明了同样的问题:
flag=0
target="hello"
for candidate in "hello" "world"
do
if [ "$target" != "$candidate" ]
then
flag=1
fi
done
if [ "$flag" -eq 1 ]
then
echo "The string was not found"
fi
这就像脚本一样每次都打印The string was not found
,即使它很明显也是如此。
这里的问题是脚本要求所有文件都匹配。它仅要求ANY文件匹配。解决此问题的最简单方法是:
flag=1
flag=1
表示已找到匹配项(而不是未找到匹配项)以下是可以正确找到字符串的版本:
flag=0
target="hello"
for candidate in "hello" "world"
do
if [ "$target" = "$candidate" ]
then
flag=1
fi
done
if [ "$flag" -eq 1 ]
then
echo "The string was found"
else
echo "The string was not found"
fi