Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sh: Test for existence of files

Tags:

People also ask

How do you check for existence of a file in shell script?

Open the “testfile.sh” in any text editor. Then write the script, save it by pressing “save”. One way is to find a file by asking for a filename from the user in the terminal. Use “-f” to check the file's existence.

How do I check to see if a file exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

How do you check if a file exists in a directory in Linux?

In Linux everything is a file. You can use the test command followed by the operator -f to test if a file exists and if it's a regular file. In the same way the test command followed by the operator -d allows to test if a file exists and if it's a directory.


How does one test for the existence of files in a directory using bash?

if ... ; then
   echo 'Found some!'
fi

To be clear, I don't want to test for the existence of a specific file. I would like to test if a specific directory contains any files.


I went with:

(
   shopt -s dotglob nullglob
   existing_files=( ./* )
   if [[ ${#existing_files[@]} -gt 0 ]] ; then
      some_command "${existing_files[@]}"
   fi
)

Using the array avoids race conditions from reading the file list twice.