Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 530
Leagsaidh Gordon Avatar asked Oct 20 '12 14:10

Leagsaidh Gordon


2 Answers

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
...
like image 180
sampson-chen Avatar answered Oct 07 '22 23:10

sampson-chen


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
like image 40
doubleDown Avatar answered Oct 07 '22 21:10

doubleDown