How to check if a file exists without creating a race condition in a bash script?

Correct me if I'm wrong but of what I know and my understanding of race conditions and TOCTOU (Time of check and time of use) bug, checking if a file exists this way:

if [ -f /path/to/file ]; then 
        #File exists continue the script

Creates a race condition and TOCTOU bug. So is there any other way of checking if a file or directory exists without creating a race condition, or maybe trying to open the file and handle errors if it doesn't exists.

I know it may be not so critical in most scripts to use the previous method but for me it's best to practice to avoid these kind of conditions.
Thanks for any help.

Read more here:

Content Attribution

This content was originally published by yankh18 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: