###? How Do I Get KM Variable in Shell Script from other Apps?
I need to get the value of a KM variable using shell scripts from other apps.
This works in KM:
but NOT in any other app.
I understand why this does not work in apps like Terminal (see below).
But is there a way to make the KM environment available to other apps, so I can get the KM variable?
BTW, I have searched extensively in the KM wiki, forum, and general google, but could not find an answer to this question.
I don't know if there is a better way, but here is one way that works, at least in Terminal.app:
osascript -e 'tell application "Keyboard Maestro Engine" to
get value of variable "File_Path"'
Note: For readability, I broke command into two lines.
I added this to the KM Wiki, but this Wiki article needs a lot of work:
Using Shell Scripts with Keyboard Maestro
1 Like
Hey JM,
That's pretty much it I do believe.
For readability I prefer to write AppleScripts embedded in shell scripts like this:
read -r -d '' theAppleScript <<'EOF'
tell application "Keyboard Maestro Engine"
tell variable "pathStr"
if it exists then
return its value
else
return "Error β Keyboard Maestro variable βpathStrβ does not exist!"
end if
end tell
end tell
EOF
osascript -e "$theAppleScript";
You don't have to fight with the shell's quoting conventions either.
-Chris
2 Likes
Thanks, Chris. I really like your code. I'll add it to the wiki.
One question: Can you add a statement at the top to set the KM variable name, so that the literal name does not have to be repeated below?
Hey JM,
You mean something like this?
read -r -d '' theAppleScript <<'EOF'
tell application "Keyboard Maestro Engine"
set kmVariableName to "pathStr"
tell variable kmVariableName
if it exists then
return its value
else
return "Error β Keyboard Maestro variable β" & kmVariableName & "β does not exist!"
end if
end tell
end tell
EOF
myAppleScriptOutput=$(osascript -e "$theAppleScript");
echo "$myAppleScriptOutput";
* Note that I've also made the AppleScript output go to a shell variable.
-Chris
Duh. I must have been asleep when I asked that question.
I was so focused on setting a shell variable that I overlooked the obvious of setting an AppleScript variable.