apk-based friendly command not found handler

command-not-found.sh 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/bin/sh
  2. # command-not-found: display useful package suggestions when a command is not found
  3. #
  4. # Copyright (c) 2017 William Pitcock <nenolod@dereferenced.org>
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in all
  14. # copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. results=$(apk search -xv "cmd:$1" 2>/dev/null)
  24. if [ "$results" ]; then
  25. printf "The program '%s' may be found in these packages:\n" "$1" >&2
  26. printf "%s\n" "$results" | while read atom _ desc
  27. do
  28. atom=${atom%-*}; atom=${atom%-*} # remove version
  29. printf " * %s: %s\n" "$atom" "$desc" >&2
  30. done
  31. printf "To install packages: 'apk add <selected package>'\n" >&2
  32. else
  33. printf "%s: not found\n" "$1" >&2
  34. fi
  35. # POSIX EX_NOTFOUND exit code
  36. exit 127