Bash 脚本未搜索给定目录

Bash script not searching a given directory

所以我正在尝试编写一个脚本来搜索用户给定的目录,以查找用户也提供的特定扩展名的所有文件。到目前为止,无论给出什么目录,我的脚本都只搜索我的主文件夹的 mybooks 目录。目前的脚本如下所示:

# Prompts the user to input a directory
# Saves input in variable dir
echo -n "Please enter a directory to search in: "
read dir
if [ ! -d /$dir ]; then
   echo "You didn't enter a valid directory path. Please try again."
fi

# Prompts the user to input a file extension to search for
# Saves input in variable ext
echo -n "Please enter a file extension to search for: "
read ext
echo "I will now search for files ending in "$ext

# Searches for files that match the given conditions and prints them
find $dir -type f -name $ext
for file in *$ext
do
echo $file
done

#TODO: put code here that prints the names of the largest and smallest files
# that were found in the search

echo "The largest file was: "
echo "The smallest file was: "

因此您可以看到从未提供 mybooks 目录。这是示例输出:

Please enter a directory to search in: /var/books
Please enter a file extension to search for: .txt
I will now search for files ending in .txt
hound.txt
list-lines.txt
numbers.txt
The largest file was: 
The smallest file was: 
$ls /var/books/
arthur-conan-doyle_The-hound-of-baskervilles.txt  arthur-conan-doyle_The-valley-of-fear.txt  mary-roberts-rinehart_The-circular-staircase.txt
arthur-conan-doyle_The-hound-of-baskervilles.zip  arthur-conan-doyle_The-valley-of-fear.zip

关于我做错了什么或从这里去哪里有什么建议吗?谢谢!

替换为:

find $dir -type f -name $ext
for file in *$ext
do
echo $file
done

有了这个:

find "$dir" -type f -name "*.$ext"

说明

find $dir -type f -name $ext

以上搜索 $dir 名称为 完全 $ext 的文件。很可能没有这样的文件。

相比之下,以下忽略 $dir 并在当前目录中搜索扩展名为 $ext 的文件:

for file in *$ext
do
echo $file
done

请注意,因为 $dir$ext 可能包含空格或其他难以理解的字符,所以它们应该用双引号引起来。