如何在没有uci实用程序的情况下改进从shell解析openwrt uci配置文件变量?

时间:2017-06-15 12:26:45

标签: shell awk configuration-files openwrt

一些基于openwrt的分支没有uci实用程序。我不想从其c源构建uci,而uci在entware-ng-3x repo中不可用。

制表符分隔 uci 配置文件如下所示:

# Whitelist regex strings examples
#   list    whitelist   '^10\.0\.[01]\..*$'
#   list    whitelist   '^192\.168\.1\..*$'

# RBL URLs - some (but not all) will also support http
    list    rbl 'https://sigs.interserver.net/iprbl.txt'
 list   rbl 'https://rbldata.interserver.net/ip.txt' 
 list   rbl 'https://rbldata.interserver.net/ipslim.txt' 

idiomatic-awk blog posthttps://unix.stackexchange.com/a/286794/17560的帮助下,我能够使用awk解析uci .conf文件(busybox 1.24 +):

$ awk '!(/^\t*#/) && /\trbl\t/ {print $3}' config/file.conf
'https://sigs.interserver.net/iprbl.txt'
'https://rbldata.interserver.net/ip.txt'
'https://rbldata.interserver.net/ipslim.txt'

可能的改进,要使用空格而不是制表符来捕获编辑器缩进,就是直接匹配第二列的值而不使用制表符,如下所示:

awk '!(/^\t*#/) && $2 == "rbl" {print $3}' 

如何进一步改进此uci配置文件解析?

PS请记住,该平台是一个带有busybox(没有gnu utils)的路由器,[:blank:]来匹配空格和标签似乎不被busybox awk理解,entware-ng-3x包安装是确定。

1 个答案:

答案 0 :(得分:1)

UCI文件的结构使得可以单独使用shell解析它(包括busybox shell)。有些脚本只是在OpenWRT中执行此操作。

首先定义三个名为config(),option(),list()

的shell函数

然后您获取UCI文件。它将config,option,list行视为带有1或2个参数的shell命令。

e.g。 UCI文件" file.conf":

config myconfigtype 'myconfiginstance'
    option myoption 'myvalue'
    option otheroption 'other value'

shell脚本" uci.inc":

config() {
    echo I got a config section type $1 instance $2
    CONF="$2"
}
option() {
    echo I got an option named $1 value $2 pertaining to config $CONF
}

主shell脚本:

#!/bin/sh
. uci.inc   # read shell library
. file.conf # parse file.conf
相关问题