0

I'm using a little code to check if some files match with each other or not then prompt a question to the user and take appropriate actions according to the user response. However, bash completely ignores my read command!

declare -i int
int=1
find ./1 -name '*.xyz' | while read FILENAME
do
find . -name '*.xyz' | while read FILENAME2
do
    if [ $FILENAME != $FILENAME2 ]; then
        if [ $(dirname "${FILENAME}") != $(dirname "${FILENAME2}") ]; then
            if [ $(basename "${FILENAME}") == $(basename "${FILENAME2}") ]; then
                int=int+1
                if cmp -s "$FILENAME" "$FILENAME2" ; then
                    echo "Match", "$FILENAME", "$FILENAME2", "$int"
                else
                    # echo "No Match", "$FILENAME", "$FILENAME2", "$int"
                    read -p "No match modify? (y/n)" d
                    echo "$d ";
                fi
                if [ "$int" -gt 44 ]; then
                    exit 1
                fi
            fi
        fi
    fi
done
done 

I am using osx. I have checked and a simple read command functions properly outside a loop on my terminal(iterm).

1
  • If you haven't done already, make sure that your script always starts with the shebang #!/usr/bin/env bash. Commented Sep 19, 2019 at 9:44

1 Answer 1

1

The entire while loop has its standard input redirected. Any read will consume one line of the input from find instead of from the user's terminal.

Running the same find command repeatedly inside the outer loop is horribly inefficient, anyway. Probably collect the results from the two find commands into two arrays, then simply loop over strings in memory instead of spinning the disk over the same directories over and over again.

However, if you are trying to find files outside 1 which are identical to files within 1 with the same name, a much more efficient approach is to run

find . -name '*.xyz' -exec shasum {} +

then process the resluting output in a simple Awk script. Perhaps something like this:

#!/bin/bash

find . -name '*.xyz' -exec shasum {} + |
# Reverse each line, sort by first field, reverse again
# Entries for files with the same basename will now be adjacent
rev | sort -t / -k1,1 | rev |
awk -F / '$NF!=p { p=$NF; delete a; c=""; }
    { split($0, x, /[ \t]+/);
        if(x[2] ~ /^\.\/1\//) { 
            if (a[x[1]]) print a[x[1]];
        c = x[1];
            next
        }
        if (c) {
            if (x[1] == c) print x[2];
            next;
        }
        a[x[1]] = x[2] (a[x[1]] ? ORS a[x[1]] : ""); }'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.