Hi All, I’m trying to set a couple of KM Variables using a shell script. So far I’ve tried:
IFS=', ' read -r -a NAMES <<< "$KMVAR_Directory" KMVAR_lastName=${NAMES[0]} KMVAR_firstName=${NAMES[1]}
where Directory is a comma separated list; lastName and firstName are KM variables. The syntax works in concept in the terminal. Not sure what I’m missing. Any help would be appreciated.
1 Like
Sorry, but you can only set KM Variables using AppleScript or JXA.
The environment of a script that Keyboard Maestro executes is configured with a copy of the values of the Keyboard Maestro variables at the time the action executes. Changing them afterwards is not something Keyboard Maestro can detect, and not a method you can use to update the Keyboard Maestro variables.
From a shell script, you can set a Keyboard Maestro variable by using the osascript tool. Something like:
osascript -e 'on run argv' -e 'tell app "Keyboard Maestro Engine" to setvariable (item 1 of argv) to (item 2 of argv)' -e 'end run' var value
Replace var and value with the (quoted) variable names and variable values, so maybe:
osascript -e 'on run argv' -e 'tell app "Keyboard Maestro Engine" to setvariable (item 1 of argv) to (item 2 of argv)' -e 'end run' "lastName" "${NAMES[0]}"
1 Like
Thanks for the conceptual explanation. The osascript solution worked perfectly.
And similarly:
#!/bin/bash
varName="someTempVar"
varValue="some temp val like 42"
osascript -l JavaScript -e "function run(argv) \
{Application('Keyboard Maestro Engine') \
.setvariable('$varName', {to:'$varValue'})}"
for:

or perhaps more flexibly:
#!/bin/bash
# Two quoted arguments: KMVarName KMVarValue
setKMVar() {
osascript -l JavaScript -e "function run(argv) \
{Application('Keyboard Maestro Engine') \
.setvariable('$1', {to:'$2'})}"
}
setKMVar "someName" "some string value"

3 Likes
And just to extend the party, here's the equivalent function for shell scripts written in Perl:
sub setKMVar {
my ($vName, $vValue) = @_;
`osascript -l JavaScript -e "function run(argv) {Application('Keyboard Maestro Engine') .setvariable('$vName', {to:'$vValue'})}"`
}
Called, for example, like this in an Execute Shell Script written in Perl:
setKMVar("countFeatures",$features);
You can read %countFeatures% in subsequent actions in the macro.
3 Likes