Set KM Variable to the Current Directory in a Shell Script?

I'm trying to set a KM variable to the path of the current directory, in a shell script.

I admit I'm not very knowledgeable about shell scripts. Here's a portion of the script I tried:

cd "/Users/Dan/Documents/Development/GitHub/TheNewbieWoodworker/"
osascript -e 'tell application "Keyboard Maestro Engine" to setvariable "DND_jekyllSite_path" to "$(dirname)"'

The variable ends up containing the text $(dirname). Anyone know what I'm doing wrong?


Hey Dan,

The big problem with your AppleScript is that you've single-quoted the whole string and thus prevented variable/command interpolation.

It's always a good practice to construct your command string before sending it to the relevant command (osascript in this case). That way you can use echo or printf to display it for debugging until you get it right, and then you can run the string with your command.

Here's how I'd probably write that:

#!/usr/bin/env bash


# Uncomment for debugging
# printf "$myDir"

cd "$myDir"

# Read is arranged to Interpolate shell variables:
read -r -d '' asCmdStr <<EOF
   tell application "Keyboard Maestro Engine"
      setvariable "DND_jekyllSite_path" to "$myDir"
   end tell

# Uncomment to verify AppleScript command syntax for debugging.
# printf "$asCmdStr"

osascript -e "$asCmdStr"

I'm reusing the cd path rather than addressing the current directory programmatically.

If you really need to do that then here's how:


pwd means Print Working Directory.


1 Like

Thanks, Chris, and that's exactly what I wanted. I would even have used a variable like that if I could figure out how. So not only am I grateful, I also approve of how you did it! (High praise, I'm sure.)

Thanks again!

1 Like