How do I check if either or both of the two files exist?

8,426

Solution 1

if test -e file1 || test -e file2; then
  # At least one of file1 or file2 exists
  ...
else
  # Neither file1 nor file2 exists
fi

test -e checks for mere existence. You may want a more specific test, such as -b (exists and is block special), -c (exists and is character special), -d (exists and is a directory), -f (exists and is a regular file) etc.

Solution 2

Both of the other answers run test twice. While this will work, it has the inefficiency of two process forks. You can get the "or" done in a single test with:

if [ -e file1 -o -e file2 ]; then ...

Which will be slightly more efficient.

Share:
8,426

Related videos on Youtube

ovuvuvew
Author by

ovuvuvew

Updated on September 18, 2022

Comments

  • ovuvuvew
    ovuvuvew over 1 year

    How can I check, in shell script, if any of two files exist?

    It doesn't matter which of the two files exist or if they both exist.

    • Eric Renouf
      Eric Renouf over 7 years
      You can find a lot of useful checks by reading man test
  • AlexP
    AlexP over 7 years
    Bash built-in test.