bash 检查文件是否在bash中的给定目录(或子目录)中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12989615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if file is in a given directory (or sub-directory) in bash
提问by Leagsaidh Gordon
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.
如何检查给定文件是否在目录中,包括具有该目录的任何目录,等等?我想在 bash 脚本中进行一个小的完整性检查,以检查用户是否没有尝试更改项目目录之外的文件。
采纳答案by sampson-chen
Use find (it searches recursively from the cwd or in the supplied directory path):
使用 find(它从 cwd 或在提供的目录路径中递归搜索):
find $directory_path -name $file_name | wc -l
Example of using this as part of a bash script:
将此用作 bash 脚本的一部分的示例:
#!/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
...
回答by doubleDown
find returns nothing (i.e. null string) if the file is not found. if [ '' ]would evaluate to FALSE.
如果找不到文件,find 将不返回任何内容(即空字符串)。if [ '' ]将评估为 FALSE。
if [ $(find "$search_dir" -name "$filename") ]; then
echo "$filename is found in $search_dir"
else
echo "$filename not found"
fi
回答by scoota269
find /path/to/dir -name "filename" | wc -lwould give you number of times the file exists within /path/to/dirand its subdirs. Any result greater than 0 would indicate the file is within the correct path. Any result equal to 0 would mean the file is not within the path or doesn't exist.
find /path/to/dir -name "filename" | wc -l会给你文件存在于/path/to/dir它的子目录中的次数。任何大于 0 的结果都表示文件在正确的路径中。任何等于 0 的结果都意味着该文件不在路径内或不存在。

