You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带花括号范围标记的IP字符串转换为IP地址数组

问题根因

Bash 仅会对代码里写死的字面量大括号做范围扩展,从输入框读取到变量里的大括号标记会被识别为普通字符串,不会自动解析生成对应的IP序列。

修复方法

核心修改

替换你代码里的ips=($iprange)行,改用eval手动触发大括号扩展:

# 解析大括号范围生成IP数组(仅自用脚本场景安全,无外部不可信输入风险)
eval "ips=($iprange)"

可选优化

原脚本ping命令未指定探测包数量,会持续发包直到超时,建议加上-c 1参数仅发1个探测包提升效率,同时可以做系统兼容处理:

# Linux 可直接用 timeout,macOS 用 gtimeout,以下写法兼容两个系统
timeout $tout ping -c 1 "$ip" 2>/dev/null || gtimeout $tout ping -c 1 "$ip"
修改后完整代码
#!/bin/bash
iprange=""
tout=""

# Dialog for entering IP range and ping timeout
dialog --colors --ok-label "Submit" \
--backtitle "Scan IP range and request timeout" \
--title "\Zb Scan range \Zn" \
--form "Set scan IP range & request timeout\n \
       \n\Zb------------------ Example ------------------ \
       \nIP range:       192.168.1.1 192.168.1.2 \
       \nIP range:       192.168.1.{10..255} \
       \nTimeout (sec):  0.1 or 1\Zn" 15 50 0 \
       "IP range:"      1 1 "$iprange"  1 15 40 0 \
       "Timeout (sec):" 2 1 "$tout"     2 15 3 0 > file.tmp \
       2>&1 >/dev/tty

# 读取输入参数
iprange=$(sed -n 1p file.tmp)
tout=$(sed -n 2p file.tmp)
rm -f file.tmp

# 解析大括号生成IP数组
eval "ips=($iprange)"

echo "Scanning for devices..."
for ip in "${ips[@]}"
do
    echo "-------------------------"
    echo "$ip"
    timeout $tout ping -c 1 "$ip" 2>/dev/null || gtimeout $tout ping -c 1 "$ip"
done
效果验证

修改后输入192.168.{1..3}.{10..12}这类多段范围标记,会自动展开为9个对应IP,离散IP输入的逻辑也不受影响。

内容的提问来源于stack exchange,提问作者Sasha Milic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:54:01