使用AWK与gsub修改dhcpcd.conf中eth0的静态IP
修改dhcpcd.conf中eth0的静态IP:问题与完善方案
需求说明
要完成的操作:搜索/etc/dhcpcd.conf文件,修改eth0对应的未注释静态IP地址。
测试用配置文件内容:
interface eth0 # test variants of comments #static ip_address=192.168.21.40/24 # static ip_address=192.168.21.40/24 #static ip_address=192.168.21.40/24 # static ip_address=192.168.21.40/24 #the line to match and change static ip_address=123.223.122.005/24
遇到的问题
参考AWK方案编写脚本时碰到两个问题:
- 替换后旧IP未完全覆盖,输出变为
static ip_address=111.222.123.234123.223.122.005/24 - 无法让AWK识别Bash变量
$new_ip,传递后输出static ip_address=sip123.223.122.005/24
尝试的测试脚本
#!/bin/bash # testing on a copy of the config file conf_file="/home/user/dhcpcd.conf" # BASH variable with fake test ip new_ip=111.222.123.234 cat "$conf_file" | awk $' /interface / { matched=0 } /interface eth0/ { matched=1 } matched { gsub( "^\\s*static ip_address=•*" , "static ip_address=111.222.123.234" ) } { print } '
最终可用但有局限的脚本
#!/bin/bash # Test reading and setting of the ip address in /etc/dhcpcd.conf using AWK # source /etc/dhcpcd.conf which always includes the lines: # interface eth0 # static ip_address=www.xxx.yyy.zzz # copy of config file for testing cfg_file="/home/user/dhcpcd.conf" # fake test ip new_ip="114.113.112.111" awk -i inplace -v sip=$new_ip $' /interface / { matched=0 } /interface eth0/ { matched=1 } matched { gsub( "^[[:blank:]]*static ip_address=.*" , "static ip_address="sip ) } { print } ' $cfg_file exit
更完善的解决方案
改进点说明
- 变量传递更安全:传递Bash变量时用引号包裹,避免特殊字符解析问题
- 正则更精准:只匹配未被注释的行,避免误改注释内容;保留原行缩进风格
- 增加备份机制:操作前自动备份原文件,防止误操作损坏配置
- 边界处理:如果eth0段没有静态IP行,自动添加配置(可选)
完善后的脚本
#!/bin/bash # 完善版:修改dhcpcd.conf中eth0的静态IP,带备份、变量安全传递 cfg_file="/etc/dhcpcd.conf" new_ip="114.113.112.111" # 生成备份文件,后缀为.bak backup_file="${cfg_file}.bak" # 先备份原文件,失败则退出 cp "$cfg_file" "$backup_file" || { echo "备份文件失败,退出"; exit 1; } awk -v new_ip="$new_ip" ' /^interface / { # 离开之前的interface段时,检查是否需要补加IP if (matched && !ip_updated) { print "static ip_address=" new_ip "/24" } matched = ($2 == "eth0") ? 1 : 0 ip_updated = 0 } matched && /^[[:blank:]]*static ip_address=/ && !/^[[:blank:]]*#/ { # 匹配未注释的静态IP行,仅替换IP部分 sub(/=[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+/, "=" new_ip "/24") ip_updated = 1 } { print } END { # 文件末尾是eth0段且未更新IP时,补加一行 if (matched && !ip_updated) { print "static ip_address=" new_ip "/24" } } ' "$cfg_file" > "${cfg_file}.tmp" && mv "${cfg_file}.tmp" "$cfg_file" echo "操作完成,原文件已备份至${backup_file}"
脚本特性
- 自动备份原文件,降低误操作风险
- 精准定位eth0段内未被注释的静态IP配置行
- 替换时保留原行缩进,不破坏配置格式
- 支持自动补加静态IP配置(当eth0段无对应行时)
- 用临时文件写入再替换,避免中途出错损坏原文件
内容的提问来源于stack exchange,提问作者dazz
相关产品推荐
相关产品推荐

