Linux bash script to extract IP address

前端 未结 13 2432
我在风中等你
我在风中等你 2020-12-04 15:44

I want to make big script on my Debian 7.3 ( something like translated and much more new user friendly enviroment ). I have a problem. I want to use only some of the informa

13条回答
  •  醉酒成梦
    2020-12-04 16:07

    In my opinion the simplest and most elegant way to achieve what you need is this:

    ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7
    

    ip route get [host] - gives you the gateway used to reach a remote host e.g.:

    8.8.8.8 via 192.168.0.1 dev enp0s3  src 192.168.0.109
    

    tr -s ' ' - removes any extra spaces, now you have uniformity e.g.:

    8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109
    

    cut -d' ' -f7 - truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:

    192.168.0.109
    

提交回复
热议问题