How do I compare file names in two directories in shell script?

前端 未结 5 908
有刺的猬
有刺的猬 2021-01-31 05:39

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


        
5条回答
  •  渐次进展
    2021-01-31 06:01

    It doesn't work because you're comparing variables that contain the directory prefix. Just remove the prefix before comparing:

    name1=${file1##*/}
    name2=${file2##*/}
    if [[ $name1 == $name2 ]]; then
        echo "$name1 exists in both directories"
    fi
    

    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.

    for file in $Dir1/*; do
        name=${file##*/}
        if [[ -f $Dir2/$name ]]; then
            echo "$name exists in both directories"
        fi
    done
    

提交回复
热议问题