getent 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/bin/sh
  2. #
  3. # Closely (not perfectly) emulate the behavior of glibc's getent utility
  4. #
  5. #passwd|shadow|group|aliases|hosts|networks|ethers|netgroup|protocols|services|rpc
  6. # only returns the first match (by design)
  7. # dns based search is not supported (hosts,networks)
  8. # case-insensitive matches not supported (ethers; others?)
  9. # may return false-positives (hosts,protocols,rpc,services,ethers)
  10. [ -z "$PATH" ] && PATH="/bin:/usr/bin" || PATH="${PATH}:/bin:/usr/bin"
  11. export PATH
  12. file="/etc/$1"
  13. case $1 in
  14. passwd|group)
  15. match="^$2:\|^[^:]*:[^:]*:$2:" ;;
  16. shadow)
  17. match="^$2:" ;;
  18. networks|netgroup)
  19. match="^[[:space:]]*$2\>" ;;
  20. hosts|protocols|rpc|services|ethers)
  21. match="\<$2\>" ;;
  22. aliases)
  23. match="^[[:space:]]*$2[[:space:]]*:" ;;
  24. ""|-h|--help)
  25. echo "USAGE: $0 database [key]"
  26. exit 0 ;;
  27. *)
  28. echo "$0: Unknown database: $1" 1>&2
  29. exit 1 ;;
  30. esac
  31. if [ ! -f "$file" ] ; then
  32. echo "$0: Could not find database file for $1" 1>&2
  33. exit 1
  34. fi
  35. if [ $# -eq 1 ] ; then
  36. exec cat "$file"
  37. else
  38. sed "s/#.*//; /$match/q; d" "$file" | grep . || exit 2
  39. fi