How to create an Automator service to run a script on all files in a folder

automatorscript

I want to create a service using Automator to run a shell script on all files in a folder, say delete all log files. What I have done is

  1. Created a new service in automator.
  2. Added a "Run Shell Script" action. I have change this to 'pwd' for now.
  3. Selected "Service receives selected folders".
  4. Tried to run it, but get a message. "To test this service within Automator, add the "Get Specified Finder Items" action to the beginning of your workflow. Remove or disable the action before running the workflow outside of Automator.
  5. OK. So I add "Get Specified Finder Items". Added a 'test' directory to the list of items.

Now, when I run the script, the results window prints out my home directory.

Elsewhere, I have read that I maybe need to add

cd "$1"

to the beginning of my script. I did that but it still prints my home directory. How do I get this thing to print the directory I have selected in "Get Specified Finder Items?"

Edited to Add

Here is a screen shot of a script that works.

test

Here is a screen shot os a script that doesn't work.

enter image description here

The usual way I would deal with the "no match found : *.log" error would be to redirect error output to null. Replacing the "rm" line by

find . -name "*.log" -print0 | xargs -0 rm -rf

Does work though. This seems more difficult than it should be.

Best Answer

If you're creating a Service using RunShell Script which you want to pass the selected Folder(s) to the RunShell Script and have additional actions take place in the script on them, then start with these settings.

Create the Service:

  1. Open Automator and select Service or File > New > Service If Automator is already open.

  2. Set Service receives selected to folders and in to Finder.

  3. Add a Run Shell Script Action, setting Shell: to /bin/bash and Pass input: to
    as arguments. This changes the default code to from cat to:

    for f in "$@"
    do
        echo "$f"
    done
    

Now you can use $f to act on the target Folder(s), e.g. cd $f and now you're in the directory of $f and can add additional code to act upon the files/folders within $f, etc.

Update:

Use the following working code as an example:

for d in "$@"; do
    cd "$d"
    for f in *.log; do    
        rm "$f"
    done
done

Within the Test and Test copy folders there were a number of .log files and files with other extensions as well. When the above code was run it deleted only the *.log files within the target folders as show in the images below using two folders or one folder and both files and folders with/without spaces in their names.


enter image description here


enter image description here