user2167582 user2167582 - 2 months ago 7
AppleScript Question

how to interpret bash variables in applescript command

I am trying to write a bash script that reloads a given chrome tab, and I am passing the variable

POSITION_STRING
to applescript to dynamically determine the definition of the statement (as I thought thats what heredocs notations are used to do).

But it seems applescript rejects this type of connotation, help?



declare -A POSSIBLE_POSITIONS
POSSIBLE_POSITIONS=(
["1"]="first"
["2"]="second"
["3"]="third"
["4"]="fourth"
["5"]="fifth"
["6"]="sixth"
["7"]="seventh"
["8"]="eighth"
["9"]="ninth"
["10"]="tenth"
)

# echo "${POSSIBLE_POSITIONS[$1]}"
POSITION=$1
POSITION_STRING=${POSSIBLE_POSITIONS[$POSITION]}
# echo $POSITION_STRING

/usr/bin/osascript <<EOF
log "$POSITION_STRING" # this works!
tell application "Google Chrome"
tell the "$POSITION_STRING" tab of its first window
# reload
end tell
end tell
EOF

foo foo
Answer
  1. AppleScript's object specifiers accept integer-based indexes just fine. There's absolutely no need to use first, second, etc keywords, and you're digging yourself a hole trying to munge them into AppleScript code.

  2. When using osascript, the correct way to pass arguments into your AppleScript is to put them after the file name (if any). osascript will then pass these arguments to your AppleScript's run handler as a list of text values, which you can then extract, check, coerce, etc. as appropriate.

Example:

POSITION=1

/usr/bin/osascript - "$POSITION" <<'EOF'
  on run argv -- argv is a list of text
    -- process the arguments
    set n to item 1 of argv as integer
    -- do your stuff
    tell application "Google Chrome"
      tell tab n of window 1
        reload
      end tell
    end tell
  end run
EOF