Skip to content

Instantly share code, notes, and snippets.

@b-mc
Created February 2, 2024 16:10
Show Gist options
  • Save b-mc/dd4743fc2199a80cbe6638bdd2e7334c to your computer and use it in GitHub Desktop.
Save b-mc/dd4743fc2199a80cbe6638bdd2e7334c to your computer and use it in GitHub Desktop.
OpenWRT UCI scripting cheat sheet

OpenWRT UCI scripting cheat sheet

Notes

I use UCI together with bash. In case of other shells the variable and loop syntax might have to be adjusted accordingly.

New config entry - indexes

  1. Reference the newly added item with [-1]:

    uci add firewall rule
    uci set firewall.@rule[-1].name=test
    

    Each newly added entry will again be available under [-1].

  2. Assign the new entry to a shell variable:

    rule=$(uci add firewall rule)
    uci set firewall.$rule.src='lan'
    
    pbr_policy=$(uci add pbr policy)
    uci set pbr.$pbr_policy.name='test'
    

    When saving to a variable, you capture the unique key of the new config entry. I prefer this method as it's more predictable in scripts and less error prone.
    In case of a new config entry, where you modify just one property, you could combine two lines into one:

    uci set pbr.$(uci add pbr policy).name='test'
    

Modify existing entries

Unnamed sections

[0] lets you hook to the first unnamed section in the config file:

config dnsmasq
        option domain 'lan'

uci set dhcp.@dnsmasq[0].domain='home'

Named sections

config adblock 'global'
        option adb_fetchutil 'curl'

uci set adblock.global.adb_fetchutil='uclient-fetch'

Quirks

While deleting, the indexes of the remaining config entries change right away without committing (uci commit), e.g. entry 1 becomes entry 0 immediately once the previous 0-indexed entry gets removed!

Real world example: you install the PBR package, and wanna delete two default PBR policies from the config file provided by the package.
You would most likely use this loop:
for i in {0..1}; do uci -q delete pbr.@policy[$i]; done
but it won't work - it would remove just the first policy!
The correct approach is:
for i in {0..1}; do uci -q delete pbr.@policy[0]; done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment