gpt4 book ai didi

linux - 编写一个函数来用硬链接(hard link)替换重复文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:55 25 4
gpt4 key购买 nike

我需要编写一个 bash 脚本来遍历指定目录的文件并用硬链接(hard link)替换文件的副本。现在,我的整个函数如下所示:

#! /bin/bash
# sameln --- remove duplicate copies of files in specified directory

D=$1
cd $D #go to directory specified as default input

fileNum=0 #loop counter

DIR=".*|*"
for f in $DIR #for every file in the directory
do
files[$fileNum]=$f #save that file into the array
fileNum=$((fileNum+1)) #increment the counter
done

for((j=0; j<$fileNum; j++)) #for every file
do
if [ -f "$files[$j]" ] #access that file in the array
then
for((k=0; k<$fileNum; k++)) #for every other file
do
if [ -f "$files[$k]" ] #access other files in the array
then
test[cmp -s ${files[$j]} ${files[$k]}] #compare if the files are identical
[ln ${files[$j]} ${files[$k]}] #change second file to a hard link
fi
done
fi
done

基本上:

  • 遍历指定目录下深度为1的所有文件
  • 将文件内容放入数组
  • 将每个数组项与其他数组项进行比较,并用硬链接(hard link)替换重复项

测试目录下有四个文件:a,b,c,d

a 和 b 不同,但 c 和 d 是重复的(它们是空的)。运行脚本后,ls -l 显示所有文件仍然只有 1 个硬链接(hard link),因此脚本似乎基本上什么也没做。

我哪里错了?

最佳答案

DIR=".*|*"
for f in $DIR #for every file in the directory
do
echo $f
done

这段代码输出

.*|*

你不应该像这样遍历文件。查看 find 命令。如您所见,您的代码无法运行,因为第一个循环已经出错。

顺便说一句,不要将变量命名为全部大写,我相信这些是为系统变量保留的。

关于linux - 编写一个函数来用硬链接(hard link)替换重复文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com