Shell脚本-无法将随机值分配给变量

时间:2020-07-28 19:50:48

标签: bash shell

我正在尝试下面的脚本根据给定的输入生成和打印IP。但是执行后我找不到命令 输入: 输入IP:155.169.10 范围:10 总数:4 实际: testing.sh:第15行:155.55.10.11:找不到命令 testing.sh:第15行:155.55.10.12:找不到命令 testing.sh:第15行:155.55.10.13:找不到命令 testing.sh:第15行:155.55.10.14:找不到命令 testing.sh:第15行:155.55.10.15:找不到命令 预期结果: 155.55.10.11 155.55.10.12 155.55.10.13 155.55.10.14

 #!/bin/bash
        echo "enter IP: xxx.xxx.xx"
        read ip;
        echo "enter range"
        read range;
        echo "total"
        read total;
        count=1
        while [ $count -le $total ];
        do
        num=$(expr $range + $count)
        #echo "$ip"".$num"
        IP=$("$ip"".$num")
        echo $IP
        count=$(expr $count + 1)
        done                   

1 个答案:

答案 0 :(得分:0)

如前所述,删除不需要的子外壳-IP="$ip.$num"

bash起,您还可以从一些性能调整中受益。试试这个-

#!/bin/bash
declare -i range total num count=1
read -p "enter IP: xxx.xxx.xx: " ip;
read -p "enter range: " range;
read -p "total: " total;
while (( count < total ));
do  num=$(( range + count++ ))
    IP="$ip.$num"
    echo "$IP"
done                   

我将输入验证作为另一个问题。 :)

更新

好吧,很有趣...
这应该验证输入本身-

#!/bin/bash
declare -i count node
read -p "enter starting IP: xxx.xxx.xxx.xxx: " ip;
IFS=. read -a node <<< "$ip"
for n in 0 1 2 3
do if [[ -n "${node[4]}" || -z "${node[$n]}" || "${node[$n]}" =~ [^0-9] ]] || (( ${node[$n]} > 255 ))
   then echo "Invalid IP '$ip'"
        exit 1
   fi
done
base="${ip%.*}"
node="${ip##*.}"
read -p "How many do you want? " count;
while (( count-- ));
do  echo "$base.$node"
    (( node++ ))
done

这仍然允许创建的IP无效,例如,如果您以IP 1.2.3.250开头并要求再输入10个。考虑也要为此签一张支票,大声笑

相关问题