awk : Need Help in Understanding a command

Hello

I am working on a Change request and Stuck at a point. The below awk command is used in the function.

float_test ( ) {
  echo | awk 'END { exit ( !( '"$1"')); }'
}

I understand that awk 'END' is used to add one line at the end and exit is used to end the script with an error code but I am not able to understand the command as a whole.

Could someone please help me on this.

Thanks
Rahul

So... I get the idea that "float_test" is passed an awk expression.

so what happens (I think this is poorly written)...

  1. echo - programmer wanted to use awk's expression evaluator but didn't use /dev/null which is probably better (?)

  2. awk doesn't add a line with END, it just performs something at the end of stream of data (in this case "echo", but again probably could have used /dev/null.

  3. The "$1" comes from the shell, in the case the argument passed to float_test where is will become a piece of awk text to be processed.

Since you place inline awk in single quotes he's breaking out the single quotes to insert the shell variable "$1". This is how you did things a long time ago or you could say this is how you do things now to be portable across different vendor version OS levels of awk like things.

So it's called "float_test", but you could use this for just about anything. Might be interesting to see how float_test gets called in the script.

Try:

float_test a=1
echo $?

float_test whatever-really-just-type-whatever
echo $?

but the following also works

float_test not-a-number
echo $?

float_test 3.14
echo $?

Which is probably close to how it's used in context

1 Like

Thanks cjcox for your help.

Assuming that the string passed in as the first positional parameter forms a valid arithmetic or logical expression, the float_test shell function returns exit status 0 if the expression evaluates to a non-zero value and returns exit status 1 if the expression evaluates to zero.

It could be written without the echo (and without redirection) if it used a BEGIN clause instead of an END clause:

float_test ( ) {
	awk 'BEGIN{exit(!('"$1"'))}'
}

If you're using a 1993 or later version of the Korn shell as your shell, you could evaluate similar expressions just using shell built-ins:

float_test ( ) {
	return $((!($1)))
}

But note that awk performs floating point arithmetic by default while ksh performs integer arithmetic by default. So, where float_test "1/3" using awk gives exit code 0 because 1/3 evaluates to 0.3333... ; but when using ksh93 gives exit code 1 because 1/3 evaluates to 0. To reverse the behaviors, int(1/3) evaluates to 0 and exits with code 1 with awk and 1./3 evaluates to 0.3333... and exits with code 0 with ksh93 .

1 Like

Thanks Don for the indepth analysis..It really helped.