使用uci命令行读取uci config小结

UCI是一个用C语言编写的小应用程序,用来集中管理OpenWrt/LEDE的所有配置选项,UCI配置文件位于目录 /etc/config/内。

假设有以下配置文件:/etc/config/v2conf,内容如下:

#这里是注释,实际使用中请删除
#每个config就是一个段落
config v2conf ‘v2name’ #段落类型是v2conf,段落名字是v2name,该段落在uci show中显示为v2conf.v2name
option enabled ‘1’ #在uci show中显示为v2conf.v2name.enabled=’1′
option server ‘s07030093’ #也可以直接读取uci get v2conf.v2name.server,

config subscriptions #这个段落是匿名的,段落类型是subscriptions,无段落名,该匿名段落在uci show中显示为v2conf.@subscriptions[0]
option address ‘http://www.baidu.com/’

config subscriptions #这个段落也是匿名的,该匿名段落在uci show中显示为v2conf.@subscriptions[1]
option address ‘http://www.google.com/’

config servers ‘server1’ #有段落名字就好读取了,uci show v2conf.server1
option name ‘name1′
option success ’62’
option total ‘129’
option uptime ‘2019-04-21 21:04:56’
#uci get v2conf.server1.uptime
#返回2019-04-21 21:04:56

config servers ‘s07030093’
option name ‘name2′
option success ’36’
option total ‘165’
option uptime ‘2019-04-21 21:25:02’

config servers ‘s61355758’
option name ‘name3’
option success ‘7’
option total ’33’
option uptime ‘2019-04-21 20:56:49′

uci命令可以直接在OpenWrt/LEDE的命令行中使用,如在控制台中输入:uci show v2conf
将显示如下内容:
v2conf.v2name=v2conf
v2conf.v2name.enabled=’1′
v2conf.v2name.server=’s07030093′
v2conf.@subscriptions[0]=subscriptions
v2conf.@subscriptions[0].address=’http://www.baidu.com/’
v2conf.@subscriptions[1]=subscriptions
v2conf.@subscriptions[1].address=’http://www.google.com/’
v2conf.server1=servers
v2conf.server1.name=’name1′
v2conf.server1.success=’62’
v2conf.server1.total=’129′
v2conf.server1.uptime=’2019-04-21 21:04:56′
v2conf.s07030093=servers
v2conf.s07030093.name=’name2′
v2conf.s07030093.success=’36’
v2conf.s07030093.total=’165′
v2conf.s07030093.uptime=’2019-04-21 21:25:02′
v2conf.s61355758=servers
v2conf.s61355758.name=’name3′
v2conf.s61355758.success=’7′
v2conf.s61355758.total=’33’
v2conf.s61355758.uptime=’2019-04-21 20:56:49′

常用uci命令:
1.uci show
用法:uci show config #显示config配置文件的所有配置
示例:
uci show v2conf #显示/etc/config/v2conf配置文件的所有配置
uci show v2conf.v2name #只显示v2conf.v2name段落

2.uci get
用法:uci get config.section.option #获取某option具体的值
示例:
uci get v2conf.v2name.enabled #获取enabled的值
uci get v2conf.v2name #如果只get到段落名,获取的是段落类型v2conf

3.uci set
用法:uci set config.section.option=value #设置某option具体的值为value
示例:
uci set v2conf.v2name.enabled=0
然后uci get v2conf.v2name.enabled 发现返回值是0

4.uci delete
4.1用法:uci delete config.section.option #删除某option
示例:
uci delete v2conf.s61355758.uptime
然后uci show v2conf.s61355758返回
v2conf.s61355758=servers
v2conf.s61355758.name=’name3′
v2conf.s61355758.success=’7′
v2conf.s61355758.total=’33’
发现uptime已删除

4.2用法:uci delete config.section #删除某段落section
示例:
uci delete v2conf.s61355758
然后uci show v2conf.s61355758返回
uci: Entry not found
段落不存在

5.uci commit
用法:uci commit config #提交修改。因为之前经过uci set/delete的值实际上都还在缓存内,重启以后就会丢失
示例:
uci commit v2conf