Leeor
Leeor

Reputation: 83

Check if same file exists in another directory using Bash

I'm new to bash and would like your help; couldn't find an answer for this case. I'm trying to check if the files in one directory exist in another directory

Let's say I have the path /home/public/folder/ (here I have several files) and I want to check if the files exist in /home/private/folder2

I tried that

for file in $firstPath/*
do
   if [ -f $file ]; then
   (ask if to over write etc.. rest of the code) 

And also

for file in $firstPath/*
do
   if [ -f $file/$secondPath ]; then
   (ask if to over write etc.. rest of the code) 

Both don't work; it seems that in the first case, it compares the files in the first path (so it always ask me if I want to overwrite although it doesn't exist in the second path) And in the second case, it doesn't go inside the if statement. How could I fix that?

Upvotes: 8

Views: 8644

Answers (1)

ghoti
ghoti

Reputation: 46826

When you have a construct like for file in $firstPath/*, the value of $file is going to include the value of $firstPath, which does not exist within $secondPath. You need to strip the path in order to get the bare filename.

In traditional POSIX shell, the canonical way to do this was with an external tool called basename. You can, however, achieve what is generally thought to be equivalent functionality using Parameter Expansion, thus:

for file in "$firstPath"/*; do
   if [[ -f "$secondPath/${file##*/}" ]]; then
       # file exists, do something
   fi
done

The ${file##*/} bit is the important part here. Per the documentation linked above, this means "the $file variable, with everything up to the last / stripped out." The result should be the same as what basename produces.

As a general rule, you should quote your variables in bash. In addition, consider using [[ instead of [ unless you're actually writing POSIX shell scripts which need to be portable. You'll have a more extensive set of tests available to you, and more predictable handling of variables. There are other differences too.

Upvotes: 7

Related Questions