4 Customizing udev Rules

The order in which rules are evaluated is important. udev processes rules in lexical order. To add custom rules, you need udev to find and evaluate these rules before the default rules.

The following example procedure shows how to implement a udev rules file that adds a symbolic link to the disk device /dev/sdb.

  1. Create the rule file in /etc/udev/rules.d.

    Create a rule file under /etc/udev/rules.d with a file name such as 10-local.rules that udev reads before any other rules file.

    The following rule in 10-local.rules creates the symbolic link /dev/my_disk, which points to /dev/sdb:

    KERNEL=="sdb", ACTION=="add", SYMLINK="my_disk"

    Listing the device files in /dev shows that udev hasn't yet applied the rule:

    ls /dev/sd* /dev/my_disk
    ls: cannot access /dev/my_disk: No such file or directory
    /dev/sda  /dev/sda1  /dev/sda2  /dev/sdb
  2. Test the new rule by using the udevadm test command.

    To simulate how udev applies its rules to create a device, you can use the udevadm test command with the device path of sdb listed under the /sys/class/block hierarchy, for example:

    udevadm test /sys/class/block/sdb
    calling: test
    version ...
    This program is for debugging only, it does not run any program
    specified by a RUN key. It may show incorrect results, because
    some values may be different, or not available at a simulation run.
    ...
    LINK 'my_disk' /etc/udev/rules.d/10-local.rules:1
    ...
    creating link '/dev/my_disk' to '/dev/sdb'
    creating symlink '/dev/my_disk' to 'sdb
    ...
    ACTION=add
    DEVLINKS=/dev/disk/by-id/ata-VBOX_HARDDISK_VB186e4ce2-f80f170d 
      /dev/disk/by-uuid/a7dc508d-5bcc-4112-b96e-f40b19e369fe 
      /dev/my_disk
    ...
  3. Restart the systemd-udevd service.
    sudo systemctl restart systemd-udevd
  4. Verify that the rule is active.

    After udev processes the rules files, the symbolic link /dev/my_disk is added:

    ls -F /dev/sd* /dev/my_disk
    /dev/my_disk@  /dev/sda  /dev/sda1  /dev/sda2  /dev/sdb
  5. (Optional) Undo the changes so that the rule and the symbolic link are removed.

    To undo the changes, remove /etc/udev/rules.d/10-local.rules and /dev/my_disk, then run systemctl restart systemd-udevd again.

    sudo rm /etc/udev/rules.d/10-local.rules
    sudo rm /dev/my_disk
    sudo systemctl restart systemd-udevd