Script which removes files from the first directory if there is a file in the second directory

Script must removes files from the first directory if there is a file with same name in the second directory

Script passed to the two directories, it lies with them in one directory:
sh script_name dir1 dir2

This is my version, but it does not work :wall:

set - $2/*
for i
do
  set - $1/*
    for j
    do
      if [ "$i" = "$j" ]
        then rm $j
      fi
    done
done

Please, write your versions of this script

P.S.
Sorry for my bad English

d1=$1
d2=$2

cd "$d1"
for file in *
do
  if [ -f "$d2/$file" ]
  then
    printf "%s exists in both\n" "$file"
  fi
done
1 Like

$ sh scrdel dir1 dir2
$ sh scrdel dir1 dir2
$ sh scrdel dir1 dir2

Thanks, but the console does not show this message "%s exists in both\n", and the file should be removed (in first directory). I have change it

printf "%s exists in both\n" "$file"

to

 rm "$file" 

and it also don't work. :confused: Please, help me.

Pass the full path to the directories (or at least to the second one), e.g.:

scrdel dir1 "$PWD/dir2"
1 Like

Thank you very much, you really helped me!!!:b: Is it impossible to write this script and it will work sh scrdel dir1 dir2 without passing the full path?:confused:

d1=$1
d2=$2

for file in "$d1"/*
do
  file2=$d2/${file##*/}
  if [ -f "$file2" ]
  then
    printf "%s exists as %s\n" "$file" "$file2"
  fi
done
1 Like

Thank you, you are the best!!!:b: