MacOS – Issue with Automator and bash script

automatorbashmacos

I'm making an automator service, and the first part takes files and RARs them using a bash script

So in Automator, I have a Get Specified Finder Items action to test the workflow, and then the bash script

F=''
for i in "$@"; do 
    F="$F \"${i//\"/\\\"}\""
done

/usr/local/bin/rar a ~/archive.rar $F

so it just takes the file paths, puts quotes around them, and then runs the RAR command with all the files as arguments. When I run this, automator gives me the error

Cannot open "/Users/user/test.txt" No such file or directory

Cannot create ~/archive.rar No such file or directory

No clue why it's getting those errors. When I add an echo to the last command

echo /usr/local/bin/rar a ~/archive.rar $F

The results are the exactly the command I need. I can copy and paste it in terminal and it works.

Does automator run bash scripts differently then they would run in terminal?

Best Answer

bash does expansion of $@ different than all other environment variables to preserve white space etc in arguments. From bash(1):

@ Expands  to  the  positional  parameters,  starting from one.  When the expansion occurs
  within double quotes, each parameter expands to a  separate  word.   That  is,  "$@"  is
  equivalent  to  "$1"  "$2" ...  If the double-quoted expansion occurs within a word, the
  expansion of the first parameter is joined with the beginning part of the original word,
  and  the  expansion  of  the last parameter is joined with the last part of the original
  word.  When there are no positional parameters, "$@" and $@  expand  to  nothing  (i.e.,
  they are removed).

So you basically should be able to call rar within the Shell Script action without any parsing:

/usr/local/bin/rar a ~/archive.rar "$@"