Bash脚本未搜索给定目录

Bash脚本未搜索给定目录,bash,unix,scripting,Bash,Unix,Scripting,因此,我试图编写一个脚本,在用户给定的目录中搜索用户提供的特定扩展名的所有文件。到目前为止,我的脚本只搜索我的主文件夹的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

因此,我试图编写一个脚本,在用户给定的目录中搜索用户提供的特定扩展名的所有文件。到目前为止,我的脚本只搜索我的主文件夹的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"
解释 上面搜索的
$dir
文件的名称正好是
$ext
。很可能没有这样的文件

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

for file in *$ext
do
echo $file
done

请注意,由于
$dir
$ext
可能包含空格或其他困难字符,因此它们应使用双引号。

感谢您的解释!然后如何在不忽略$dir的情况下回显find命令的结果?@MFonner默认情况下,
find
将回显它找到的每个名称。我希望
find$dir-type f-name$ext
不会回显任何名称,因为没有一个文件的整体名称与
$ext
匹配。非常感谢。我打错了一个参数。
for file in *$ext
do
echo $file
done