Using find in a bash script - how to handle case where find returns "file or directory does not exist"

I use the find command in my bash script so

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

However, how do I handle the case where the entry in my script is a file / directory that does not exist? (i.e. I want to print a message when this happens)

I tried using -d and -f, but the case I am having problems with is $ {1} is. "or".."

When the input is that which does not exist, it does not enter my for loop.

Thank!

+5
source share
4 answers

Bash scripts are a bit weird. Practice before implementation. But this site seems to have broken it well.

If the file exists, this works:

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

, . '!' "":

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

Bash :

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

Assign the find to a variable and test it.

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

You can try something like this:

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

All Articles