Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

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

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
function asort() { … }
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

Your Answer


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.