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

Solution 1:

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" || exit
    for f in *.log; do 
        [ -f "$f" ] || continue   
        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.

Note: The screen shots below do not contain the error handling that was added to the example shell script code per comments to this answer.


enter image description here


enter image description here