Bash – Weird “No such file” error with “xargs” and “file”

bashshellxargs

I'd like to get the MIME type of all files under the current directory. Why doesn't this work? I've tested bash on OSX or Linux. "file" complains that it can't find the file, but if I run it with the exact same path it works.

$ find . -type f | xargs -n 1 -I FILE echo $(file --mime-type -b FILE)
ERROR: cannot open './foo.txt' (No such file or directory)
...
$ file --mime-type -b ./foo.txt
text/plain

Of course in the real world I don't just "echo" the response, I need to use the MIME type string in another command.

This is the simplest I could make the problem. I guess I'm not understanding something about xargs filename substitution?

Best Answer

The command substitution $(file --mime-type -b FILE) is executed by the shell before being passed to xargs, which is why you are not seeing what you need. Quote $(file --mime-type -b FILE) and pass it to bash -c via xargs

find . -type f | xargs -n 1 -I FILE bash -c  'echo $(file --mime-type -b FILE)'
Related Question