Search code examples
bashopenwrt

How do I loop inside a file and create a new one following a template in Openwrt?


I have a template for policy routing for OpenWRT and I have tons of IP's that I need to insert in this file.

Basically I have all ips I need in a file called bunchofips And this is the template I need to follow:

config rule 'rule1'
    option dest_ip 'ipcomeshere'
    option proto 'all'
    option use_policy 'secondary'
    option sticky '1'
    option src_ip '192.168.1.1/24'

Basically where is written rule1 I need it to increase by 1 for each IP. So if I have 300 ips, the last one will be rule300. The ipcomeshere is where it should get from the file bunchofips, this file is like this:

150.100.32.0/20
130.3.220.0/22
185.5.188.0/22
192.153.127.0/24
112.153.64.0/18
[...]

So what kind of script could I have to make this new file with all this ips and to be able to run in a OpenWRT router? Is that even possible?

Thanks!


Solution

  • I don't know what format you want the output in (eg, single file, 300x files, pass as stdin to another process) so for the sake of this answer I'll just dump the output to a single file 'allmyconfigs'.

    I'm also going to assume you want an entire line from 'bunchofips' to replace 'ipcomeshere', eg, replace 'ipcomeshere' with '150.100.32.0/20'.

    For this answer we'll use a simple echo template with a couple variables to customize the output for each pass through the loop, eg:

    > allmyconfigs                 # start with an empty file
    
    counter=0
    
    while read -r newip
    do
        counter=$((counter+1))
    
        echo "config rule 'rule${counter}'
        option dest_ip '${newip}'
        option proto 'all'
        option use_policy 'secondary'
        option sticky '1'
        option src_ip '192.168.1.1/24'" >> allmyconfigs
    
    done < bunchofips