Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Big Dave

macrumors 6502
Original poster
Nov 27, 2007
314
25
Crestview, Fl
I would like to read in a variable into a BASH script using awk. I am failing at the correct syntax. Could someone help?
Code:
variable=`awk '{ if ( $x >= .9 ) print " 254 0 0"
                     else if ( $x >= .8 ) print " 0 254 0"
                     else print " 0 0 254 "}'`
 
Do you want the $x to expand to the then-current value of the shell variable 'x'?

If so, you'll have to do something about the single-quotes, because single-quotes prevent all shell-variable expansion.

I can post an answer, but I need to know what you want from the $x.
 
Do you want the $x to expand to the then-current value of the shell variable 'x'?

If so, you'll have to do something about the single-quotes, because single-quotes prevent all shell-variable expansion.

I can post an answer, but I need to know what you want from the $x.

chown33,
You nailed me last time on an expansion error. I will really be ashamed if I have made the same mistake. To give you a little more information, $x will be a value from 0 to 1. It can have as many as 8 places following the decimal. I script mainly in BASH and I know that decimals are bad in BASH. I was hoping that awk could handle the job. I basically want to make some conditions to where $x falls between 0 and 1. I want to then assign a three variable array based on the comparison.
 
Last edited:
Here's the answer (well, one possible answer):

Code:
variable=`awk </dev/null -v xyzzy="$x" 'END { if ( xyzzy >= .9 ) print " 254 0 0"
                     else if ( xyzzy >= .8 ) print " 0 254 0"
                     else print " 0 0 254 "}'`

There were multiple problems:

1. Single-quotes were preventing the expansion of $x in the quoted program. Oops.
2. You didn't give awk any input, so it's reading stdin. Not good.
3. If you gave it an empty input stream, then no pattern-match will occur, so no output. Not good.

To solve these:

1. I avoided adding escaped double-quotes by using an awk variable (xyzzy),
which is assigned a value by the -v option.
2. I gave it /dev/null to read from, which will give an immediate EOF.
3. I used the special pattern END, which is executed when EOF occurs on input.
 
Obviously I need to properly learn how to use expansion. I admit I am a novice. I really appreciate your help. Thanks again!
 
You're welcome.

At least you ask interesting questions that don't look like homework or LMGTFYable. And you post code first time.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.