在bash脚本中使用find - 如何处理find返回“文件或目录不存在”的情况

时间:2013-01-23 03:52:54

标签: bash find

我在bash脚本中使用find命令,如此

for x in `find ${1} .....`;
do
    ...
done

但是,如何处理我的脚本输入是不存在的文件/目录的情况? (即我想在发生这种情况时打印出一条消息)

我尝试过使用-d和-f,但我遇到问题的情况是$ {1}是“。”或“..”

当输入不存在时,它不会进入我的for循环。

谢谢!

4 个答案:

答案 0 :(得分:2)

Bash为您提供了开箱即用的功能:

if [ ! -f ${1} ];
then
    echo "File/Directory does not exist!"
else
    # execute your find...
fi

答案 1 :(得分:0)

Bash脚本有点奇怪。实施前练习。但this site似乎打破了它。

如果文件存在,则可以:

if [ -e "${1}" ]
then
  echo "${1} file exists."
fi

如果文件不存在,则可以。注意'!'表示'不':

if [ ! -e "${1}" ]
then
  echo "${1} file doesn't exist."
fi

答案 2 :(得分:0)

将查找分配给变量并对变量进行测试。

files=`find ${1} .....`
if [[ "$files" != “file or directory does not exist” ]]; then
  ...
fi

答案 3 :(得分:0)

您可以尝试这样的事情:

y=`find . -name "${1}"`
if [ "$y" != "" ]; then
  for x in $y; do
    echo "found $x"
  done
else
  echo "No files/directories found!"
fi
相关问题