Bash script to get all IP addresses

后端 未结 12 2281
-上瘾入骨i
-上瘾入骨i 2020-12-28 22:51

I am trying to write a bash script to get all IP addresses on a server. The script should work on all major distros. Here is what I have:

ifconf         


        
12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 23:13

    It's a very tricky solution but it works:

    ip a | awk ' !/[0-9]+\: lo/ && /^[0-9]\:/ || /inet / && !/127\.0\.0\.1/ {print $2}'

    Output:

    eth0: 192.168.0.1/24

    Better yet:

    ip a | awk ' !/[0-9]+\: lo/ && /^[0-9]\:/ || /inet / && !/127\.0\.0\.1/ {print $2}' | perl -i -pe "s/:\n/: /g;" -pe "s/\/[\d]+$//"

    Output:

    eth0: 192.168.0.1

    I don't have a machine with several non loopback interfaces I can check it with, feel free to post your findings.

提交回复
热议问题