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

前端 未结 5 929
有刺的猬
有刺的猬 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:02

    Your comparison fails because Dir1/foo is not the same as Dir2/foo. Instead, if you change to one directory, your * will expand to just the filenames:

    #!/bin/bash
    
    Dir1="$1"
    Dir2="$2"
    
    if ! cd "$Dir1"; then
      echo "ERROR: Couldn't find directory $Dir1" >&2
      exit 1
    fi
    
    if [[ ! "$Dir2" =~ ^/ ]]; then
      echo "ERROR: Second directory must be a full path." >&2
      exit 1
    fi
    
    for file1 in *; do
        if [ -f "$Dir2/$file1" ]; then
            echo "$file1 is contained in both directories"
        fi
    done
    

    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.

提交回复
热议问题