1

Can I create an awk variable in a one liner using bash command substitution techniques? Here is what I am trying, but something is not right.

awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 1 ) print "there is a load"  }'

Perhaps it's because the command substitution uses Awk (though I doubt it)? Maybe that's too "Inception-ish"? GNU Awk 3.1.7

GL2014
  • 6,016
  • 4
  • 15
  • 22

4 Answers4

3

Why use a variable here at all? So far as AWK reads stdin unless you explicitly specify the opposite, that should be a preferable way:

$ uptime | awk '$(NF-2) >= 1 { print "there is a load" }'
there is a load
Dmitry Alexandrov
  • 1,693
  • 12
  • 14
1

There is nothing wrong with your command. Your command is waiting for an input and that's the only reason why it doesn't get executed!

For instance:

$ awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 0 ) print "there is a load"  }'
abc                 ## I typed.
there is a load     ## Output.

Just include BEGIN in your command as suggested by the experts!

$ awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 0 ) print "there is a load"  }'
there is a load
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mano Nadar
  • 26
  • 3
0

Since the last awk command does not have an input file, you can only use a BEGIN clause for that script. So you can try the following:

awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 1 ) print "there is a load"  }'
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
0

This:

awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 1 ) print "there is a load"  }'

needs a BEGIN as others have stated:

awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 1 ) print "there is a load"  }'

but also, you don't need to call awk twice as that can be written as:

awk -v uptime=$(uptime) 'BEGIN{ n=split(uptime,u); AVG=u[n-2]; if ( AVG >= 1 ) print "there is a load"  }'

or more likely what you want:

uptime | awk '{ AVG=$(NF-2); if ( AVG >= 1 ) print "there is a load"  }'

which can be reduced to:

uptime | awk '$(NF-2) >= 1 { print "there is a load"  }'
Ed Morton
  • 188,023
  • 17
  • 78
  • 185