Create an automator service calling a bash script and passing arguments I am trying to automate a bash script which calls pandoc. I would like to highlight a markdown file in finder, then select the 'md2tex' service, which will turn the markdown file into a .tex file. I have got this to run fine in the terminal. However, when I try to automate it, it doesn't work. When I open Automator, I create a new service, then a drag and drop 'run shell script' into the window on the right. Other options are shown in the window below. I have used the $@ symbol to refer to the variable name (name of file). The screenshot shows all of the options / settings.



I get a weird error message 'syntax error at -e line 1'. Any help appreciated.
First, change the Shell pop-up from /usr/bin/perl to /bin/bash. That's what's causing the error -- it's trying to run the script with perl, and it's not in valid perl syntax.

Second, the script itself needs some work. $@ expands to all arguments (in this case, the paths of all selected files), but your script expects just one item. If you don't want it to fail if multiple items are selected, you should either just have it operate on the first, or make it loop over all of the items. looping is usually what you want, and in fact when you add that action to your Automator service it should auto-fill a template for looping over the items. Next, you need to put double-quotes around all references to file paths (and variable references in general) or it'll be hopelessly confused by file/folder names with spaces. Next, the path(s) it's going to receive will include the full filename, including ".md", so adding another ".md" will make it fail. To get the output filename, you may want to remove the ".md" before adding ",tex".

Here's my quick stab at a script:

for f in "$@"
do
    if [[ "$f" = *.md ]]; then
        /path/to/pandoc -s --template=generic.latex "$f" "${f%.md}.tex"
    fi
done


You'll need to fill in the full path to the pandoc executable, in place of "/path/to/pandoc" in the script. You can probably fund this by running the command which pandoc in your regular shell.

I made it skip anything other than ".md" files; you might want to change that part. If so, you might need to generalize the "${f%.md}.tex" part -- that removes a ".md" extension before adding ".tex", but if the input file has some different extension it'll just tack on ".tex" in addition to whatever's there. Warning: don't use "${f%.*}.tex" because in some cases that'll remove part of the directory name the file's in!

Oh, and for actual use as a Finder service, you need to remove the "Get Selected Finder Items" action -- that's good for testing in Automator, but you need to remove it or it'll add whatever's selected in the Finder to what it's supposed to run on (probably meaning it runs twice on everything).