How to automatically add module to /etc/modules if it doesn't exist

check_module() {
  local module="$1"
  if grep -Fxq "$module" /etc/modules
    echo "$module already exists in /etc/modules"
    echo "$module not found in /etc/modules. Adding it now..."
    echo "$module" | sudo tee -a /etc/modules

check_module "i2c-dev"

This script will at the module if it doesn’t exist in /etc/modules yet.

Note that it will only detect if exactly the same line as the argument to check_module is already present in /etc/modules. For example if i2c-dev option1=value1 is in /etc/modules, the script will only detect this line correctly if you call it like

check_module "i2c-dev option1=value1"

but not if you call it like

check_module "i2c-dev"