Check if same file exists in another directory using Bash Check if same file exists in another directory using Bash unix unix

Check if same file exists in another directory using Bash


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   fidone

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.


This works too

`[[ /home/public/folder/$file -ef  /home/private/folder2/$file ]] && echo "Same files" || echo "Not same"`