Search code examples
bashshellunixautomator

Check if files of a given type exist in bash shell


I want to use Automator in my Mac with the shell to tidy up my files. I try to write some command like this:

mv -f /Users/myname/Downloads/*.zip /Users/myname/Downloads/zip/
mv -f /Users/myname/Downloads/*.txt /Users/myname/Downloads/txt/

and they worked. But I found that 'mv' will return error if no file matches, so I want to make something like this.

if (txt file) , mv *.txt /txt/
if (zip file) , mv *.txt /zip/

I found that the if statement is using

[ -f "   "]

Then I wrote something like this

[ -f "/Users/myname/Downloads/*.zip" ] && mv -f /Users/myname/Downloads/*.zip /Users/myname/Downloads/zip/ || echo 'Nothing'

But it returns "Nothing" even the files exist.

How can I fix this problem? Or I should not using shell command to do this? Any suggestion?


Solution

  • How about using find instead? Something like this:

    If you can use mv -t

    find /Users/myname/Downloads/ -maxdepth 1 -name "*.zip" -print0 | xargs -0 mv -f -t /Users/myname/Downloads/zip/
    

    If you're unlucky (or use -exec as pointed out in several comments):

    find /Users/myname/Downloads/ -maxdepth 1 -name "*.zip" -print0 | xargs -I {} -0 mv -f {} /Users/myname/Downloads/zip/
    

    EDIT added -print0 to make the solution white space safe.

    EDIT2 use mv -t instead of {}