Automator won’t execute the bash shell script

automationautomatorbashcommand linescript

I have a bash script that works like a thread. Now I'd like to turn it into a service with Automator.

Input is set to Image Files in Automator and the shell script action is set to Pass input as arguments.

The problem:

Automator takes issue with two things:

  1. The function
  2. The if condition

However, no error shows up in the log and the shell script result is empty:

(
  ""
)

What the script does:

The function createDatePath checks if the passed image is formated like 2020-08-10-demo_image.jpg and creates a folder YEAR/MONTH/ in the target directory. The if condition performs actions on the input depending on whether it's an JPEG or an PNG, and whether the date string is followed by a -qq- string. This is a trimmed down version of the script (I have some of more if conditions, but we don't need them here I guess).

The script:

backup=/Users/me/Desktop/A/backup/
targetPath=/Users/me/Desktop/A/output/

function createDatePath {
    [[ "$i" =~ ^([0-9]{4})-([0-9]{2}) ]] && \
    mkdir -p "$targetPath${BASH_REMATCH[1]}/${BASH_REMATCH[2]}";
}
for i in "$@"; do
    cp "$i" "$backup"
    if [[ "$i" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})-([^q]{2}).+\.((jpg)|(jpeg))$ ]]; then
        createDatePath;
    else
        exit 0;
    fi
done

Screen shot:

Demo Mode

Link to complete shell script: https://gist.github.com/pattulus/a89be63478174853d667

If anyone could explain to me why this doesn't work and how to make it work that'd be great.

PS: In the non-Automator script the first thing I did was cd into the source path, but I since this will end up as a service which takes files as input my guess was that I can omit this (adding cd "$@" didn't do any good).

Best Answer

The arguments Automator passes to the script are absolute paths. You can convert them to basenames with something like i=${i##*/}.