Search code examples
bashzshdiffwildcardzshrc

Compare same type of files from 2 diferent directories : zshrc function


I have posted a long time ago a question about how to compare same type (extension) files from 2 different directories:

Issue with wildcards into arguments of a Bash function

Under bash shell, everything is working fine but now, I am under zsh shell and the function below doesn't work any more:

function diffm() {for file in "$1"/$2; do diff -q "$file" "$3"/"${file##*/}"; done ;}

I get the following error:

$ diffm dir1 *.f90 dir2
diff: camb.f90/bessels.f90: Not a directory

camb.f90 and bessels.f90 are in the same directory, it is a very strange error.

I would like to use it like this (like under bash shell):

$ diffm . *.f90 ../../dir2

Is there a workaround to fix this?

Update

Here a working version on bash shell of this function:

function diffm() {
  # First dir
  dir1="$1"
  # Second dir
  dir2="${@: -1}"
  # Add slash if needed
  [[ "$dir1" != */ ]] && dir1=$dir1"/"
  [[ "$dir2" != */ ]] && dir2=$dir2"/"
  # Wildcard filenames
  files=( "$dir1"${@:2:$#-2} )
  # Compare the files
  for file in "${files[@]}"
    do
      diff -q "$file" "$dir2""${file##*/}"
    done;
  }

I am looking for the equivalent for zsh shell.


Solution

  • You should restructure the order of arguments :

    function diffm() {
        local dir2="$1" dir1="$2"; shift 2
        for file; do 
            diff -q "$dir1/$file" "$dir2/$file"
        done 
    }
    
    diffm ../../dir2 . *.f90
    

    zsh version :

    #!/usr/bin/env zsh
    
    function diffm() {
        setopt nullglob
        local dir1="$1" files="$2" dir2="$3" file1 file2
        for file1 in "$dir1"/${~files}; do
            file2="${file1##*/}"
            diff -q "$file1" "$dir2/$file2"
        done
    }
    
    diffm dir1 "*.f90" dir2