How to escape spaces etc. in when passing variable to shell

My goal:

  1. Get path of Finder item
  2. Save path to variable
  3. Use $KMVAR_ to execute shell script with variable as argument

For example:

wc -l $KMVAR_MyFile
(where the variable MyFile is set to /Users/jack/myfile.csv)

So far, so good. But if the path has a space or weird character in it, I need to be able to quote the path. If I were doing this outside of Keyboard Maestro, I would do it like this:

wc -l '/Users/jack/my file with spaces.csv'

If I run that exact line of code in a shell script action within Keyboard Maestro—no variable—it works fine. But when I try to use a variable, it fails. In fact, it fails:

  • If I don't quote the path
  • If I quote it before saving it to a KM variable
  • If I quote the actual $KMVAR… text inside the shell script

How do I pass a path string through a KM variable to a shell when the path string has spaces?

P.S. I assume I could regex out all offending characters to make the path shell-friendly, but that seems like a hack. I'm guessing that's not the "right" way to solve this problem.

Line Count - 3 Test.kmmacros (2.4 KB)

Put the reference to the $KMVAR_ variable in quotes in the script. It’ll work just fine.

Thanks @DanThomas. That causes the shell to interpret the $KMVAR string literally. I get this error:

wc: $KMVAR_FinderPath: open: No such file or directory

Sure you spelled it right? Here’s a one-line shell script I use:

chmod +x “$KMVAR_BitBarMenuExample__PluginFileName”

It works fine.

1 Like

Just to double-check, you have a variable named “FinderPath”, right?

@DanThomas I was using single quotes!! :tired_face: Ugh. Problem solved. Thank you!

Oh wow! I would never have guessed. I must have just gotten lucky using double-quotes.

Glad it’s working now, and a good lesson learned for both of us.

1 Like

Hey Jack,

Oops.  :sunglasses:


Single-quotes always make a string completely literal.

Double-quotes allow interpolation.



Very useful. Thanks, gentlemen!