对于我的作业,我必须检查目录中的两个文件是否具有相同的内容,如果是,请用另一个硬链接替换另一个。我的脚本看起来像:
cd $1 # $1 is the directory this script executes in
FILES=`find . -type f`
for line1 in $FILES
do
for line2 in $FILES
do
(check the two files with cmp)
done
done
我的问题是我无法弄清楚条件表达式以确保两个文件不相同:如果目录包含文件a,b,c和d,则不应返回true以检查a 。我该怎么做?
编辑:所以我有这个:
cmp $line1 $line2 > /dev/null
if [ $? -eq 0 -a "$line1" != "$line2" ]
但它会对文件进行两次计数:它会检查a
和b
,然后检查b
和a
。出于某种原因,将<
与字符串一起使用不起作用。
编辑:我想我弄清楚了,解决方法是在\
之前使用<
答案 0 :(得分:1)
使用test
或其别名[
:
if [ "$line1" < "$line2" ]
then
check the files
fi
请注意,我在这里使用的是<
而不是!=
(否则会有效),这样,一旦您将a
与b
进行了比较,就赢了稍后将b
与a
进行比较。
答案 1 :(得分:0)
这是一种优化的方法,可以正确处理带有嵌入空格或类似文件的文件:
find . -type f -exec sh -c '
compare() {
first=$1
shift
for i do
cmp -s "$first" "$i" || printf " %s and %s differ\n" "$first" "$i"
done
}
while [ $# -gt 1 ]; do
compare "$@"
shift
done ' sh {} +