Search code examples
bash

Check if file is in a given directory (or sub-directory) in bash


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.


Solution

  • 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
    ...