getopt.awk (1155B)
1 # Copyright 2021 Jacob R. Edwards 2 # License: GPLv3 3 # Awk shift and getopt functions 4 # 5 # Shift shifts ARGV to the left by one and updates ARGC. 6 # 7 # Getopt returns zero on success and an error of the form 'offending 8 # character: error message' on failure. Options are accessed with the 9 # global hash-map opts, where opts[char] is either true or the given 10 # argument. 11 12 function shift() 13 { 14 for (i = 2; i <= ARGC; ++i) 15 ARGV[i - 1] = ARGV[i]; 16 --ARGC; 17 } 18 19 # Only optstr is required, the others are overwritten anyway. 20 function getopt(optstr, chars, len) 21 { 22 for (; ARGV[1]; shift()) { 23 len = split(ARGV[1], chars, ""); 24 if (chars[1] != "-") 25 return 0; 26 if (len == 2 && chars[2] == "-") { 27 shift(); 28 return 0; 29 } 30 31 for (i = 2; i <= len; ++i) { 32 if (index(optstr, chars[i] ":")) { 33 if (i < len) { 34 opts[chars[i]] = substr(ARGV[1], i + 1); 35 break; 36 } else if (ARGV[2]) { 37 opts[chars[i]] = ARGV[2]; 38 shift(); 39 } else { 40 return chars[i] ": Requires an argument"; 41 } 42 } else if (index(optstr, chars[i])) { 43 opts[chars[i]] = 1; 44 } else { 45 return chars[i] ": Not an option"; 46 } 47 } 48 49 shift(); 50 } 51 52 return 0; 53 }