简体   繁体   English

如果我可能没有收到所有4个八位位组作为输入,如何使用Bash将IP地址分成4个八位位组变量?

[英]Using Bash how can I seperate an IP address into 4 Octet variables if I might not receive all 4 Octets as input?

I am writing a script that will be running in bash. 我正在编写一个将在bash中运行的脚本。

The expected input for this program will look like one of the following 4 cases: 该程序的预期输入将类似于以下4种情况之一:

run 192.168.1.1 [Other Parameters] 运行192.168.1.1 [其他参数]

run 168.1.1 [Other Parameters] 运行168.1.1 [其他参数]

run 1.1 [Other Parameters] 运行1.1 [其他参数]

run 1 [Other Parameters] 运行1 [其他参数]

Given any of these cases I want to have the following array. 考虑到这些情况中的任何一种,我希望具有以下数组。

IP[0]=192 IP [0] = 192

IP[1]=168 IP [1] = 168

IP[2]=1 IP [2] = 1

IP[3]=1 IP [3] = 1

The 4th Octet will always be required. 始终需要第四个八位位组。 If the others are not supplied they will default to 192.168.1.x. 如果未提供其他,则默认为192.168.1.x。

I saw this page on seperating Octets but I was not sure how to account for the 4 different input cases I will need to handle. 我在分隔八位字节上看到了此页面,但不确定如何处理我需要处理的4种不同输入情况。 Here. 这里。

Any help or suggestions on how I could improve or implement this would be greatly appreciated. 对于如何改进或实施此功能的任何帮助或建议,将不胜感激。

Thanks. 谢谢。

First, split the IP address into 4 parts, but only after "padding" it to guarantee 4 fields: 首先,将IP地址分为4部分,但只有在对其进行“填充”后才能保证4个字段:

input=168.1.1
IFS=. read -a o <<< "...$input"

Then, build the patched output, using default-value parameter expansion to patch the fields that were assigned null strings from the padding. 然后,使用默认值参数扩展构建修补输出,以修补从填充中分配了空字符串的字段。

declare -a ip=( ${o[-4]:-192}
                ${o[-3]:-168}
                ${o[-2]:-1}
                ${o[-1]:-1} )

And finally, you can stitch it back together: 最后,您可以将其缝合在一起:

output=$( IFS=.; echo "${ip[*]}" )

This should work. 这应该工作。 It uses a brute force to find the length of the IP, and the $IFS variable to separate it into the array: 它使用蛮力找到IP的长度,并使用$ IFS变量将其分成数组:

#! /bin/bash
function full_ip () {
    if [[ $1 = *.*.*.* ]] ; then
        echo $1
    elif [[ $1 = *.*.* ]] ; then
        echo 192.$1
    elif [[ $1 = *.* ]] ; then
        echo 192.168.$1
    else
        echo 192.168.1.$1
    fi

}

for ip in 192.168.1.1 168.1.1 1.1 1 ; do
    f=$(full_ip $ip)
    echo -n $f$'\t'
    IFS=. IP=($f) IFS=$' \t\n'
    echo ${IP[0]} ${IP[1]} ${IP[2]} ${IP[3]}
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM