Better way to detect if a given name is a valid kernel module?

To detect if a given kernel module is valid (not if it's loaded or not, but if it is available in the system), it's possible to run modprobe in dry-mode and it will answer. Currently I can output this in code by just doing this and making a grep matching the words "not found". But I don't think that output is guaranteed, for example, if it happens to be translated. Is there a better way to do this?


In my Debian 10 the exit status from modprobe --dry-run … reflects if there was any error. No surprise, the exit status is basically for this.

Examples (shell code):

  • modprobe --quiet --dry-run loop       && echo "loop - valid"
    modprobe --quiet --dry-run garbage123 && echo "garbage123 - valid"
    
  • modprobe --quiet --dry-run loop       || echo "loop - invalid"
    modprobe --quiet --dry-run garbage123 || echo "garbage123 - invalid"
    
  • if modprobe --quiet --dry-run loop; then
       # code to run when valid
       echo "loop - valid"
    else
       # code to run when invalid
       echo "loop - invalid"
    fi
    

I noticed I don't have to be root to use modprobe --dry-run like this.


Some tools use their exit status not solely to indicate errors. E.g. if grep finds nothing then it will return 1 (which usually indicates failure). When I read you used grep to tell if there was a match, I thought you tested the exit status of grep. The point of this answer is you can (and should) test the exit status of modprobe instead.