How to pass variable in bash script to osascript

I've spent hours researching this question, but none of the answers that I've found seem to work. I want to pass a POSIX path to some AppleScript running in a shell script, but nothing that I've tried lets AppleScript use the variable.

Here's something that shows (in the simplest possible form) what I'm trying to do (my actual script will use Microsoft Word to open the file named in the path and then save it to another format):

#!/bin/bash

INFILE="$1"

osascript << 'EOD'
display dialog "$INFILE"
EOD

I've tried escaping the quotes; I've tried double-single-double quotes; I've tried parentheses and braces; I've tried using the filename as a parameter and setting a variable to item 1 of argv. Nothing works that I've tried. The answer is probably obvious to any expert, and I'll be grateful for any help.


Solution 1:

You need to pass the variable as an argument to osascript instead.

This is discussed in depth at osascript how to pass in a variable - Stack Overflow.

here is the correct safe way to sanitize arbitrary strings through all three levels of code generation:

bar='$test" \t#est*;say bad script' # a proper nasty test string

osascript -  "$bar"  <<EOF

    on run argv -- argv is a list of strings
        tell application "Terminal"
            do script ("echo " & quoted form of item 1 of argv)
        end tell
    end run

EOF