1

I'm trying to use /usr/bin/file to detect file types in a program but also would like it to report if the file does not exist. However the command always returns exit status 0.

Besides grepping the output, is there a way to make /usr/bin/file exit non-zero on file not found? Or is there another command that has this behavior?

  • Are you sure the the exit status is 0, I tried the same thing on bash shell, i.e trying to find the file type of non existing file, it works fine and the exit status is 1. Try printing echo $? in bash after file command to check the exit status. – Gaurav Pundir Mar 17 '16 at 7:02
  • Also, let us know how you are capturing the exit status of command. – Gaurav Pundir Mar 17 '16 at 7:05
  • file non-existent.png; echo $? non-existent.png: cannot open 'non-existent.png' (No such file or directory) 0 – chakrit Mar 17 '16 at 9:11
  • sorry the comment formatting is a little cramped. I'm on OSX, could that be the reason? But this also happens on my build server, which is centos i think. – chakrit Mar 17 '16 at 9:12
  • Also I'm on zsh – chakrit Mar 17 '16 at 9:13
3

The man page for file on my fedora, which is similar to centOS says explicitly that filesystem errors are not considered as an error in the exit status.

However, it also mentions the -E flag which you can use:

On filesystem errors (file not found etc), instead of handling the error as regular output as POSIX mandates and keep going, issue an error message and exit.

  • Confirming this works on CentOS! But not on OSX unfortunately :( I guess I'll just stick to the ruby solution. – chakrit Mar 18 '16 at 6:24
2

As far as other commands, Ruby can figure out whether files exist:

File.exists?('filename.txt')

You can incorporate it like this:

if File.exists?(filename)
  # Use the `file` command
else
  # Handle file not existing
end

If you do this multiple times, you can clean things up a bit by moving it into a Ruby method that handles all that and returns what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.