Bash for loop with awk and variables

I'm relatively new to bash scripting and am trying to use awk inside a bash for loop but am having a problem with the variables.

for i in $(seq 30 5 60)
do

# Define variables up and down in AWK
eval $(awk 'BEGIN{ print "up=$((i+1))"}' < /dev/null)
eval $(awk 'BEGIN{ print "down=$((i-1))"}' < /dev/null)
echo $up
echo $down

# Print the longitude ($2) if the lattitude ($1) is between i =+/-1 and the age ($3) is less than 5
awk '{if ($1<$up && $1>$down && $3<5) print $2}' SWIR_age.xya > junk

# Display the profile number and average longitude
echo Profile $i
cat junk | awk '{sum+=$1} END {print sum/NR}'

done

# Remove junk
find . -name junk\* -exec rm {} \;

The echo command reads out the variables correctly but the next awk command can't read them. I've tried having the variables with and without the $ to no avail.

I'd also like to print all of this to a file at the end with the first column being profile$i and the second being the final value of sum/NR but again I am not sure how to do this.

Thanks,
Lily

$up and $down in the awk script won't be expanded due to the single quotes. Be careful - in the script, $1 et al. are awk fields, not the shell script's positional parameters. And why do you use that dangerous (eval!) and cumbersome method to define the two variables? $i will not be available within awk - see above (will not be expanded, and if, would be an internal field). Nor will the shell arithmetic expression work.

awk is not part of bash. awk is its own separate, independent language. Variables defined in BASH won't be defined in AWK unless you bring them in with -v VAR= at the beginning or VAR=... at the end.

If you run awk 5 times, you will be running it 5 independent times, with variables not carried between.

Variables inside single quotes ' ' do not expand -- and since awk code uses $ for column instead of variable, you don't want them to expand! The shell would eat them all and change the meaning of the awk code.

There's a couple ways to put variables into awk, none of which is embedding them inside the program itself.

awk -v VAR="$SHELLVARIABLE" '{ print VAR }' ...

awk '{ print VAR }' VAR="$SHELLVARIABLE" ...

awk does not need cat's help to read a file. You do this without the cat earlier, I'm not sure why you add it later.

Your awk code can be simplified so you only run it once instead of twice, and to get rid of the 'junk' file completely.

awk '($1<UP && $1>DOWN && $3<5) { TOTAL+=$2; TN++ } ; END { if(TN) print TOTAL/TN }' UP=$((i+1)) DOWN=$((i-1)) SWIR_age.xya