digitalbyte
digitalbyte

Reputation: 95

awk shell variables not working

Hi I'm using GNU awk version 3.1.5 and I've specified 2 variables in a KSH script

PKNAME= ls -lt /var/db/pkg | tr -s " " | cut -d" " -f9
PKDATE= ls -lt /var/db/pkg/$PKNAME/ | tr -s " " | cut -d" " -f6-8

I'm trying to prove that I'm getting the correct output, by running a test using

echo bar    
awk -F, -v pkname="$PKNAME" -v pkdate="$PKDATE" 'BEGIN{print pkname, pkdate, "foo"; exit}'
echo baz

The output from this results in 2 blank spaces and foo, like so

bar
  foo
baz

I have tried, double quoting the variables, single quotes and back ticks. Also tried double quotes with back ticks.

Any ideas why the variables are not being executed? I'm fairly new to awk and appreciate any help! Thanks

I suppose it is possible that it is not possible to run a sub shell comand within an awk statement. Is this true?

Upvotes: 1

Views: 741

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74695

This has nothing to do with awk. The problem is in the way you're assigning your variables. Your lines should be like this:

PKNAME=$(ls -lt /var/db/pkg | tr -s " " | cut -d" " -f9)

There can be no spaces around either side of an assignment in the shell.

At the moment, you're running the command ls -lt ... with a variable PKNAME temporarily assigned to an empty string. In subsequent commands the variable remains unset.

Your awk command should remain unchanged, i.e. the shell variables should be passed like -v pkname="$PKNAME". As an aside, it's generally considered bad practice to use uppercase variable names, as these should be reserved for internal use by the shell.

Upvotes: 1

Related Questions