Search code examples
bashoutputstderrio-redirectioncmp

bash shell script not working as intended using cmp with output redirection


I am trying to write a bash script that remove duplicate files from a folder, keeping only one copy. The script is the following:

#!/bin/sh

for f1 in `find ./ -name "*.txt"`
do
    if test -f $f1
    then
        for f2 in `find ./ -name "*.txt"`
        do
            if [ -f $f2 ] && [ "$f1" != "$f2" ]
            then
                # if cmp $f1 $f2 &> /dev/null # DOES NOT WORK
                if cmp $f1 $f2
                then
                    rm $f2
                    echo "$f2 purged"
                fi 
            fi
        done
    fi 
done 

I want to redirect the output and stderr to /dev/null to avoid printing them to screen.. But using the commented statement this script does not work as intended and removes all files but the first..

I'll give more informations if needed.

Thanks


Solution

  • &> is bash syntax, you'll need to change the shebang line (first line) to #!/bin/bash (or the appropriate path to bash.

    Or if you're really using the Bourne Shell (/bin/sh), then you have to use old-style redirection, i.e.

    cmp ... >/dev/null 2>&1
    

    Also, I think the &> was only introduced in bash 4, so if you're using bash, 3.X you'll still need the old-style redirections.

    IHTH