How can I check if a given file is in a directory, including any directories with that directory, and so on? I want to do a small sanity check in a bash script to check that the user isn't trying to alter a file outside the project directory.
Use find (it searches recursively from the cwd or in the supplied directory path):
find $directory_path -name $file_name | wc -l
Example of using this as part of a bash script:
#!/bin/bash
...
directory_path=~/src/reviewboard/reviewboard
file_name=views.py
file_count=$(find $directory_path -name $file_name | wc -l)
if [[ $file_count -gt 0 ]]; then
echo "Warning: $file_name found $file_count times in $directory_path!"
fi
...
find returns nothing (i.e. null string) if the file is not found. if [ '' ]
would evaluate to FALSE.
if [ $(find "$search_dir" -name "$filename") ]; then
echo "$filename is found in $search_dir"
else
echo "$filename not found"
fi
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