Getopt
September 17, 2019
As I have said previously on this blog, I’m not allowed to write Scheme code at work; it would never make it past code review. But I can write shell scripts, and Awk is a natural language to use in shell scripts, so lately I have been writing a lot of Awk programs.
I recently had occasion to write an Awk program that took command-line arguments, so naturally I googled “getopt.awk” and found an implementation in the Gnu Awk manual. But that version of getopt
was very C-like and not at all Awk-ish, so I decided to write my own. My getopt
function extracts command-line arguments into an associative array OPTS
that has the flag as its key and the value associated with the flag as its value; the value is null if the flag has no associated value. The getopt
function takes two arguments — a string defining the available flags, in the same format as the C getopt
function, and a string containing a message to be printed on error — and returns the number of arguments found.
Your task is to write a getopt
function for your favorite langauge; if your language already provides command-line argument handling, write a version for Awk. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.