How do I access a KM variable from inside an AWK script executed from KM "Execute Shell Script" Action?

Awk receives the KM Var if the KMVAR is one of Awk's arguments like my "$KMVAR_Input_Filename_Var" and my "$KMVAR_MyVar" below.

Awk does not receive the KM Var (I get a runtime Awk error) if the KMVAR is an actual part of the Awk code e.g. my "$KMVAR_KM_Flag_Var" below. Have I got the KMVAR syntax wrong? Thanks.

#! /usr/bin/env bash

awk -v MyVar="$KMVAR_MyVar"   ' 
{ if ( $1 = "$KMVAR_KM_Flag_Var" ) {print $1} }
'    "$KMVAR_Input_Filename_Var"

KMVAR_MyVar and KMVAR_KM_File_Var are environment variables, preset by Keyboard Maestro to the value in the corresponding Keyboard Maestro variables.

The shell will interpolate environment variables within double quotes, but not within single quotes. Hence in your example, KMVAR_MyVar will be interpolated (expanded) to its value because it is within double quotes, but KMVAR_KM_Flag_Var will not since it is within single quotes. Thus awk will see the condition $1 = "$KMVAR_KM_Flag_Var". If awk also expanded environment variables in double quotes, then this would work, but presumably it does not. Apparently, awk uses the ENVIRON facility to access environment variables, so try something like $1 = ENVIRON["KMVAR_KM_Flag_Var"]

1 Like

Hey Steve,

See this.

-Chris

1 Like