Building a BASH Shell Command that's stored in a KM Variable

Is it possible to build a BASH Command in a KM Variable and then have it executed from an "Exec Shell Command" action? I get Shell errors when I try to do this as shown. Was trying to keep it all inside KM rather than executing from a text "script file". Thanks.

Awk Command in Variable.kmmacros (2.6 KB)

56

Hey Steve,

Yes.

Please post a working version of the script at hand, so I have something real to test with.

-Chris

I've edited the OP with a more accurate Awk script.

Hey Steve,

This works:

Awk Command in Variable.ccstone v1.00.kmmacros (2.4 KB)

NOTE:

You need to be very careful doing this sort of thing.

Keyboard Maestro can change the way text-tokens are processed in the Gear Menu in the upper-right corner of the Execute a Shell Script action.

That can throw your command some monkey wrenches during assembly.

Eval can also make mischief. You should read up on it on StackExchange.

I've copied the Keyboard Maestro variable into another Bash variable and provided a printf statement for eyeballing/debugging. (eval should be turned off [commented-out] during that.)

It's a good practice to always build and test your shell scripts outside of Keyboard Maestro and make sure you get things running correctly, before you move things over to KM.

I use BBEdit's Shell Worksheets for this most of the time, but I also use the Terminal and a spiffy $15.00 app called CodeRunner.

-Chris

1 Like

Thanks Chris - it works.

Good info on BASH Eval and Security is here: http://mywiki.wooledge.org/BashFAQ/048

1 Like

Why not make it easy on yourself and:

  1. Set a KM Variable to the script
  2. Write the KM Variable to a temp file
  3. Execute Shell Script using that file.

That lets you avoid the "eval" issue that Chris @ccstone mentions.

But honestly, what not just use script file without a KM variable?

I do this all the time with AppleScript, JXA, JavaScript, and complicated Shell Scripts. The advantages:

  1. Can use script editors / IDEs outside of KM that are much better for composing and testing
  2. Script files can use Finder tags, and can be easily found using Spotlight, both direct and in the Finder.

To make it even easier, I put all of my script files in a "Script" folder inside my main KM folder, and I have a KM Dictionary to provide this path, so all I have to do is enter the script file name.

My system may or may not work for you, but I have enjoyed using it for several years now.