action to populate selected_text, run shell script, paste result - async issue?

Hello. I'm trying to create an action that will let me press a key combo with text selected (but not copied), and end up replacing that text with something that has been processed via regular expressions.

I've been using this: Find and Replace in Selected Text as a starting point, but have ran into some weird issues.

If I have it run a shell script that does a pbcopy, everything works fine.

If I have that same script run the osascript/javascript magic to process selected_text, it does not. In fact, BTT will continue to the next step BEFORE that particular block of code finishes. It's almost as if it's being forked off and running that particular osascript part asynchronously. In the end, I end up with the PREVIOUS contents of the clipboard being pasted automatically with a ⌘V action, although if i manually hit ⌘V right after, it's the NEW contents.

I've tried adding in delays both in the shell script and in BTT between the actions, but to no avail.

Is there something special about an osascript call in a shell script that lets BTT continue to the next action, even though the shell script itself hasn't finished? Any thoughts?


Here's the script I'm testing with - just replaces all "a" with "b":


echo before >> /tmp/pb
pbpaste >> /tmp/pb

echo >> /tmp/pb
osascript  -l JavaScript <<EOF

var BetterTouchTool = Application('BetterTouchTool');
BetterTouchTool.includeStandardAdditions = true;

var result = BetterTouchTool.get_string_variable("selected_text");
result = result.replace(/a/g, "b");



echo now >> /tmp/pb

pbpaste >> /tmp/pb

echo >> /tmp/pb
echo >> /tmp/pb