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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With