gpt4 book ai didi

linux - 用硬链接(hard link)替换重复文件的功能

转载 作者:太空狗 更新时间:2023-10-29 11:18:40 26 4
gpt4 key购买 nike

我需要编写一个 bash 脚本来遍历指定目录的文件并用硬链接(hard link)替换文件的副本。

到目前为止,我已经遍历文件并将文件名存储在一个数组中。

现在,我需要遍历该数组并检查每个文件是否有重复项。我用来执行此操作的相关代码如下:

#"files" is the array with all the file names
#"fileNum" is the size of the array

...

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
...

测试目录有两个文件:a和b。 b 是 a 的副本。

运行脚本后,ls -l 显示所有文件仍然只有 1 个硬链接(hard link),因此脚本似乎基本上什么也没做。

我哪里错了?

最佳答案

首先,不要遍历所有文件两次,否则您将每对文件比较两次,并且您会将文件与文件本身进行比较。其次,(( )) 中不需要美元符号。最后,我认为您没有正确访问数组,所以 [ -f ] 总是失败,因此什么也没有发生。请注意,这也需要更改您的第一个循环(使用 [ -f ] 时的数组符号。

第二个循环应该是这样的:

for((k=j+1; k<fileNum; k++)); do
if [ -f ${files["$k"]} ]; then
cmp ${files["$j"]} ${files["$k"]}
if [[ "$?" -eq 0 ]]; then
rm ${files["$k"]}
ln ${files["$j"]} ${files["$k"]}
fi
fi
done

如果此处的cmp 成功,它将创建一个链接。 cmp 只有在文件不同时才会失败。试试这个代码,当你有任何问题时让我知道。

或者:

for((k=j+1; k<fileNum; k++)); do
if [ -f ${files["$k"]} ]; then
cmp ${files["$j"]} ${files["$k"]} && ln -f ${files["$j"]} ${files["$k"]}
fi
done

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

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