How to save a variable to KM from shell script?

I would like to create a macro where I clone a repository and then open it in VS Code. I have made this thus far :

a: clone repo to ~:play and open.kmmacros (25.7 KB)

Since I cannot sadly use command code that is an external command provided by VS Code, I thought I would pass in a variable from a shell script however I don't get how I can do it. I read the wiki on shell scripts and found nothing there.

I tried to 'save results to clipboard' of that shell script however it has the annoying logging of 'cloned repo' which I do not need. Is there some way I can extract a variable from a shell script?

Thank you for any help.

You must have missed this:
Execute a Shell Script action (KM Wiki)

You cannot set a KM variable from a Shell Script directly, so you have to use AppleScript via the osascript command:

osascript -e 'tell application "Keyboard Maestro Engine" to setvariable "My KM Var" to "Some new value"'

1 Like

Yeah I saw that actually but wasn't fully sure how that worked.

I tried this :

a: clone repo to ~:play and open.kmmacros (26.1 KB)

But that doesn't seem to work. It returns nothing. I am not sure if I can actually expand $dest_dir there.

It’s strange, perhaps I am calling my variable wrong.

Although as it says here, %Variable%MYPATH% should work.

Or I made a mistake with osascript -e 'tell application "Keyboard Maestro Engine" to setvariable "MYPATH" to "$dest_dir line

I doubt $dest_dir is being properly expanded.
See Quoting Strings

I have read the post by @peternlewis there and it was really interesting. I tried to wrap dest_dir in quotes like he has it there :

`osascript -e ‘tell application “Keyboard Maestro Engine” to setvariable “MYPATH” to " “$dest_dir” "’

However that does not modify the variable at all, I don’t think it expands either.

Finish the script with:

echo $dest_dir

And then the last line of the script output (which is currently on the clipboard) will be the path (probably you want to change the output to be a variable instead of the System Clipboard). Extract the last line from that using a regex or For Each with the Lines collection.

Alternatively, you need to get the $dest_dir outside the single quotes, something like:

osascript -e 'tell … to "'$dest_dir'"'
1 Like

Thank you @peternlewis and @JMichaelTX

This works amazingly well. :yellow_heart: