0

I'm using the following function to find duplicates in a list of hash codes:

delete_duplicates() {
    let deleted_files=0
    echo "deleted_files $deleted_files"

    while read dup; do
        let count=1
        grep "$dup" $1 | while read file_hash; do
            if [[ $count -eq 1 ]]; then
                let count++
                continue
            else 
                file="$(echo "$file_hash" | cut -d ' ' -f 3-)"
                rm "$file"
                if [[ $? != 0 ]]; then 
                    echo "Error deleting the file $file"
                    exit 1
                fi
                echo $deleted_files
                let deleted_files++
            fi
        done
    done < $2

    echo "${deleted_files} files have been deleted"
}

The part where I call this function is:

get_hash_list > $hash_list
get_duplicates $hash_list > $duplicates
delete_duplicates $hash_list $duplicates

The inputs for the function are temp files.

I want to count the number of deleted files, but adding with let doesn't work as expected. The output is the following:

$ bash duplicateFinder.sh
deleted_files 0
0
1
2
3
0
1
2
3
...
0 files have been deleted

Is like the variable deleted_files is being redeclared every N files deleted.

I've tried adding 1 with let deleted_files++ and with let deleted_files+=1

  • 2
    https://mywiki.wooledge.org/BashFAQ/024 . Check your script with shellcheck – KamilCuk Aug 24 '22 at 20:34
  • `let` is an artifact of pre-POSIX shells; it's been outdated since the early 90s standardized shell arithmetic with `$(( ))` -- as in `count=$(( count++ ))` -- though one can also use the bash-local syntax `(( ++count ))` on its own. See https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Aug 24 '22 at 20:38
  • but, yup, BashFAQ #24 is right on-point. – Charles Duffy Aug 24 '22 at 20:39
  • @kamilCuk Thank you! If I use a file as input for the ```while```, it works. – Jose Constenla Aug 24 '22 at 20:42
  • @CharlesDuffy Using ```count=$((count + 1))``` does the same. ```count``` is redeclared in each ```while``` iteration. Thank anyway! I'll stop using ```let``` as suggested – Jose Constenla Aug 24 '22 at 20:48
  • Yes, I didn't say that not using `let` would fix the problem. (If it were a fix, I would be adding an answer, not commenting). – Charles Duffy Aug 24 '22 at 20:53

0 Answers0