3

I have tried really hard but could not figure out a way to print an error if

find -name \"filename"

does not find any file. The code I am using so far is as follows:

    char *argv[];
       argv[0]="find";
       argv[1]="-name";
       argv[2]=strcat(str,"\abc.txt"); 
       argv[3]=NULL;
       pid_t pid;
       pid= fork();

   if(pid==0)
   {
    execvp(argv[0],argv);
   printf("file does not exist");
    }

But I can't print my print statement because find -name \"filename" never returns an error.

ASGM
  • 11,051
  • 1
  • 32
  • 53
husnain
  • 31
  • 1
  • 2

3 Answers3

1

You can use the shell condition, such as:

[ "$(find /opt -name '*.txt')" ] && echo Found || echo Not found

which is basically the same as:

[ "$(find /opt -name '*.txt')" '!=' '' ] && echo Found || echo Not found

If you're using GNU find, try using -quit.

kenorb
  • 155,785
  • 88
  • 678
  • 743
0

I am very late to this question, but I just found an elegant answer :-)

find . -type d -empty -and -not -name . -print -exec rmdir {} + | \
  awk '{print} END {if (NR == 0) {exit(1)}}'

find here looks for empty directories in the current directory,
removes the empty directories,
prints the name of removed directories to the pipe,
awk prints the output of find and if no output is found NR == 0, bails out with an error code.

This means I can now iteratively remove empty directories:

while find . -type d -empty -and -not -name . -print -exec rmdir {} + | \
  awk '{print} END {if (NR == 0) {exit(1)}}'; \
do echo; done

Replace "my" find parameters with yours, keep the awk part either as is or without the {print} if you do not want to see the output of find in the terminal, and "voilà".

asoundmove
  • 1,292
  • 3
  • 14
  • 28
-2

try to using:

find -f PATTERN

after used this construction, you have a result code by:

echo $?

if PATTERN was not exists, this result code must be 1 (or not equals zero in some cases)