Right now, this is what my code looks like:
#!/bin/bash
Dir1=$1
Dir2=$2
for file1 in $Dir1/*; do
for file2 in $Dir2/*; do
if [[ $file1 == $file2 ]]; then
echo "$file1 is contained in both directories"
fi
done
done
I am trying to compare the file names of the two directories entered and say that the file is in both directories if the filename matches. When I try to run it though, nothing is echo-ed even though I have the same file in both directories.
It doesn't work because you're comparing variables that contain the directory prefix. Just remove the prefix before comparing:
Also, nested loops seems like an inefficient way to do this. You just need to get the filenames from one directory, and use a simple file existence check for the other directory.
Your comparison fails because
Dir1/foo
is not the same asDir2/foo
. Instead, if you change to one directory, your*
will expand to just the filenames:Note that this only matches file names. If you want to make sure it's really the same file, you should use
cmp
to compare them.I just tested this and it worked:
If you want to know what's common to two directories then this is another way with much less coding.
See
man comm
for more information about thecomm
utility.Files that are in both
Dir1
andDir2
:Files that are in
Dir1
but not inDir2
:Files that are in
Dir2
but not inDir1
: