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

如何在Bash的for循环中使用seq或范围参数遍历指定序号的IP地址

Bash遍历指定范围IP的实现方案

完整修改后代码

#!/bin/bash
mapfile -t ip < SippIPs.txt
total_ips=${#ip[@]}

echo "当前可用IP总数为: $total_ips"
echo
read -p '请输入起始序号(从1开始计数): ' start
read -p '请输入结束序号: ' end
echo

# 输入合法性校验
if ! [[ $start =~ ^[0-9]+$ && $end =~ ^[0-9]+$ ]]; then
    echo "错误:请输入有效数字"
    exit 1
fi
if (( start < 1 || end > total_ips || start > end )); then
    echo "错误:输入范围不合法,有效范围为 1-$total_ips,且起始序号不可大于结束序号"
    exit 1
fi

for ((j=start; j<=end; j++)); do
        ips=${ip[j-1]}
        echo "$j"

        echo "    ----  正在启动第 $j 个SIPp  ----  "
        sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root@$ips <<EOF1
        screen -S sipp -d -m bash -c 'cd /usr/local/src/sipp-3.3; ulimit -Hn 65535; ulimit -Sn 65535; ./sipp -i $ips -mi $ips -sf HA_demo.xml -inf HA_demo.csv 10.171.0.231:5060 -p 5060 -r 1 -rp 1s -l 1 -m 1 -watchdog_minor_threshold 1500 -watchdog_major_threshold 4000 -watchdog_major_maxtriggers 30 -trace_err -aa -d 350s -oocsn ooc_default -t u1 -trace_screen -skip_rlimit && exec bash'
        exit
EOF1
done

可选优化:支持单输入框输入范围

如果需要支持直接输入10-20格式的范围,可将上述代码里的两个read输入行替换为以下代码:

read -p '请输入序号范围,格式为 起始-结束 (例如10-20): ' range
IFS='-' read -r start end <<< "$range"

内容的提问来源于stack exchange,提问作者Asad Javed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:36:03