group.awk 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # group.awk --- functions for dealing with the group file
  2. #
  3. # Arnold Robbins, arnold@skeeve.com, Public Domain
  4. # May 1993
  5. # Revised October 2000
  6. # Revised December 2010
  7. BEGIN {
  8. # Change to suit your system
  9. _gr_awklib = "/usr/libexec/awk/"
  10. }
  11. function _gr_init( oldfs, oldrs, olddol0, grcat,
  12. using_fw, using_fpat, n, a, i)
  13. {
  14. if (_gr_inited)
  15. return
  16. oldfs = FS
  17. oldrs = RS
  18. olddol0 = $0
  19. using_fw = (PROCINFO["FS"] == "FIELDWIDTHS")
  20. using_fpat = (PROCINFO["FS"] == "FPAT")
  21. FS = ":"
  22. RS = "\n"
  23. grcat = _gr_awklib "grcat"
  24. while ((grcat | getline) > 0) {
  25. if ($1 in _gr_byname)
  26. _gr_byname[$1] = _gr_byname[$1] "," $4
  27. else
  28. _gr_byname[$1] = $0
  29. if ($3 in _gr_bygid)
  30. _gr_bygid[$3] = _gr_bygid[$3] "," $4
  31. else
  32. _gr_bygid[$3] = $0
  33. n = split($4, a, "[ \t]*,[ \t]*")
  34. for (i = 1; i <= n; i++)
  35. if (a[i] in _gr_groupsbyuser)
  36. _gr_groupsbyuser[a[i]] = gr_groupsbyuser[a[i]] " " $1
  37. else
  38. _gr_groupsbyuser[a[i]] = $1
  39. _gr_bycount[++_gr_count] = $0
  40. }
  41. close(grcat)
  42. _gr_count = 0
  43. _gr_inited++
  44. FS = oldfs
  45. if (using_fw)
  46. FIELDWIDTHS = FIELDWIDTHS
  47. else if (using_fpat)
  48. FPAT = FPAT
  49. RS = oldrs
  50. $0 = olddol0
  51. }
  52. function getgrnam(group)
  53. {
  54. _gr_init()
  55. return _gr_byname[group]
  56. }
  57. function getgrgid(gid)
  58. {
  59. _gr_init()
  60. return _gr_bygid[gid]
  61. }
  62. function getgruser(user)
  63. {
  64. _gr_init()
  65. return _gr_groupsbyuser[user]
  66. }
  67. function getgrent()
  68. {
  69. _gr_init()
  70. if (++_gr_count in _gr_bycount)
  71. return _gr_bycount[_gr_count]
  72. return ""
  73. }
  74. function endgrent()
  75. {
  76. _gr_count = 0
  77. }