Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am writing an awk program and I want it to run it both with mawk and gawk. I need a sorting function. I have written my own, but I want to use the builtin asort() function in gawk if available.

How do I know from inside my program if the asort() function is available ?

More generally, how can I test if a function (e.g. gensub()) is available ?

share|improve this question
add comment

2 Answers

There's no portable way to test if a function exists in Awk. If you're calling the Awk script from a shell, you can make Awk calls to test for the existence of functions first.

if awk 'BEGIN {asort(a)}' <>/dev/null 2>/dev/null; then
  define_asort=
else
  define_asort='
function asort() { … }
'
fi
awk "$define_asort"'
  … rest of script …
'

If you're only trying to distinguish GNU Awk from others, you can test on some other GNU Awk feature. Calling an undefined functions causes a fatal error in Awk, but using an undefined variable is always fine and returns an empty value. You can in particular use PROCINFO[version], which since Gawk 3.1.4 contains the Gawk version number.

function my_sort(a) { … }
function sort_wrapper(a) { if (PROCINFO["version"]) asort(a); else my_sort(a); }
share|improve this answer
add comment

I can suggest an hack to determine if you are running mawk or gawk. Here it is

BEGIN {
  file = ARGV[0] " -W version 2>&1 | head -1"
  file | getline
  if ($1 == "mawk")
    print "mawk"
  else if ($2 == "Awk")
    print "gawk"
  close(file)
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.