我对 bash 很陌生。我上周才开始学习。我正在尝试搜索文件名。 如果找到文件,如何显示消息?
这就是我拥有的,但它一直说“不”
echo ' [Enter] a file name '
read findFile
if [[ -n $(find /$HOME -type f -name "findFile") ]]
then
echo 'yes'
else
echo 'no'
fi
最佳答案
几个问题:
- 定义变量时使用
var=
或read var
,使用时使用$var
。 没有理由在找到一个文件后继续搜索,所以做类似下面的事情,其中
的结果find
将在找到一个文件后-quit
并返回它是-print
#!/bin/bash echo ' [Enter] a file name ' read findFile if [[ -f $(find "$HOME" -type f -name "$findFile" -print -quit) ]]; then echo 'yes' else echo 'no' fi
请注意选项
-quit
将在 GNU 和 FreeBSD 操作系统上工作(这意味着这在大多数情况下都可以工作),但是例如,您需要将其更改为-在 NetBSD 上退出
。 可以看到this answer从 Unix/Linux StackExchange 获取有关此选项的详细信息。
另请注意,根据 Adaephon's comment , 虽然 $HOME
前面不需要 /
,但没有错,文件仍然会被找到。
关于linux - 如果 find 不为空,如何显示 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22805204/