LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash script: how to check stderr after command "find" (https://www.linuxquestions.org/questions/programming-9/bash-script-how-to-check-stderr-after-command-find-738589/)

Vilmerok 07-08-2009 07:22 AM

bash script: how to check stderr after command "find"
 
I use command "find" in my bash script: if the filename exist command find work quiet, and if the filename not exist I see the message "find: /tmp/filename: No such file or directory".


My problem is following, i want to have in my script something like this:

find "/tmp/filename" -type f -delete | "if no_any_errors execute command1" , if file_not_found execute command2"

Does it possible?

colucix 07-08-2009 07:35 AM

The error message is due to the fact that you use the name of the file you want to look for as the search path of the find command. Usually find is in the form
Code:

find /tmp -name filename
this looks recursively inside the /tmp directory for a file called filename. Output is null if any file is found, otherwise the file names are printed out. In both cases the exit code of the command is 0. Anyway, using the file name in place of the search path, as in your example, the exit code is 1 due to the error and 0 otherwise.

However if you do
Code:

find "/tmp/filename" -type f
and a directory called /tmp/filename/ exists, the find command looks for any file inside that directory and the exit status is 0.

What I am trying to tell is that the find command is not suitable for the task you want to achieve, because the exit code of find is not strictly related to the existence of the file you're searching. If you're looking for the existence of a particular file, just use test -f and act accordingly to the result. For example:
Code:

if [ -f /tmp/filename ]
then
  echo file found
  command1
else
  echo file not found
  command2
fi



All times are GMT -5. The time now is 12:48 PM.