How to pass a file set as a variable from AppleScript to a Bash shell script

applescriptbash

I've got a two part problem.

  1. I am trying to pass a variable from AppleScript to be used as a variable inside a bash shell script. I cannot figure out how to this work. I have read about concatenating the variable and the do shell script command with & inside AppleScript. But that doesn't really work with a longer script.

Here is the short AppleScript to select a file and (hopefully) pass it along to the shell as a variable.

tell application "Finder"
    activate
    choose file
    set myFile to result as text
end tell
do shell script "/path/to/script.sh"

And then the shell script itself:

#!/bin/bash
while read lines
do
    echo ${lines##*:}
    grep "string" 
done <$myFile | awk '!x[$0]++' |\
trans -b :en # this is where the second problem occurs

This is a shortened version of the actual script but I think the intent is clear. I am unsure how to pass the myFile variable FROM Applescript to the shell.

  1. The second problem is that the trans command (which is a rather handy command line translator) uses the gawk command which of course is installed along with the trans program itself. But when run from Applescript I get the error message:

error "/usr/local/bin/trans: line 4990: gawk: command not found" number 127

I know that AppleScript needs the fullpath in order for this to work. But how do I provide the full path for a command embedded deep within nearly 5000 lines of code? Do I alter the code of the trans program itself to provide the full path to gawk?

Also I realize that I could do the whole thing from within the shell and that a lot of this is adding complexity where none is needed. But I think it is still worthwhile to know how to do this.

Thanks for reading.

Best Answer

The first problem can be solved by exporting the path inside the do shell script part:

tell application "Finder"
    activate
    choose file
    set myFile to result as text
end tell
do shell script "export MYFILE=" & quoted form of myFile & " ; /Users/user_name/bin/sh/echo_var_myfile.sh"

In my example "echo_var_myfile.sh" is

#!/bin/bash
echo $MYFILE >> /Users/user_name/echo_var_myfile.txt

The executable bit has to be set:

chmod +x /Users/user_name/bin/sh/echo_var_myfile.sh

The result is the path to the chosen file.

You mustn't add a second do shell script for the shell script because as soon as the first one runs it dies and no values are exported.