Josiah
Josiah

Reputation: 37

My awk user function isn't working in a bash script

I am trying to write an awk script in ubuntu as a non-admin user. It takes four terminal statements and throws them into variables. Those variables then are sent to a function I made and it spits out an average number and prints it.

Here is my script:

#!/usr/bin/gawk -f
BEGIN{
one = ARGV[1];
two = ARGV[2];
three = ARGV[3];
four = ARGV[4];

function average_funct(one, two, three, four) 
{
total = one + two;
total = total + three;
total = total + four;
average = total / 4;
return average;
}

print("The average of these numbers is " average_funct(one, two, three, four));
}

To run it I have been using this:

./myaverage4 2 7 4 3

Which results in this error message:

gawk: ./myaverage4:9: function average_funct(one, two, three, four)
gawk: ./myaverage4:9: ^ syntax error
gawk: ./myaverage4:15:    return average;
gawk: ./myaverage4:15:    ^ `return' used outside function context

If anyone could help me figure out the problem that would be awesome.

Upvotes: 2

Views: 149

Answers (1)

Ed Morton
Ed Morton

Reputation: 204258

You can't declare a function inside the BEGIN section or any other action block. Move it outside of all action blocks.

function foo() { ... }
BEGIN { foo() }

I assume you have some reason for writing your code the way you did rather than the more obvious and adaptable to any number of arguments:

function average_funct(arr,    total, cnt) 
{
  for (cnt=1; cnt in arr; cnt++) {
    total += arr[cnt]
  }
  return (--cnt ? total / cnt : 0)
}
BEGIN {
  print "The average of these numbers is", average_funct(ARGV)
}

Upvotes: 3

Related Questions