N
N
noob4ik22017-11-29 04:21:05
linux
noob4ik2, 2017-11-29 04:21:05

How to determine ip through bash script?

Hello everyone, tell me how to determine ip in bash? For example, there is such a pwgen utility and in the script I can specify something like this mysql -uroot -p$pass_pwgen
How can I make it so that I can write $ip in the script and so that the ip of the server in the terminal of which the script was launched is registered in the configs. I want to do such a plan:
echo "host $ip" > /etc/rclocal

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Saboteur, 2017-11-29
@noob4ik2

A server can have multiple IP addresses, multiple interfaces, and they can work with different routes.
What exactly do you want?
ifconfig to parse? or ip addr show?
If there is only one external interface, then the usual
hostname -I will do.

A
Andrey Stepanov, 2017-11-29
@leoykt

ip route get 1 | awk '{print $NF;exit}'

E
Eugene, 2017-11-29
@zolt85

If you know the name of the interface, then you can try this

#!/bin/bash
IP=$(ifconfig eth0 | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')
echo "My IP is $IP"

Again, this will work adequately if there is only one interface (excluding lo), if there are several such interfaces, then something more serious needs to be written.

C
CityCat4, 2017-11-29
@CityCat4

In the simplest case, when there is only one network card, no bells and whistles - first netstat -in to get a list of interfaces and their names and discard lo0, and then ifconfig on the interface that remains.
But this is the simplest case. Even a computer with one network card can have, for example, a virtual machine and a bridge that already combines at least two interfaces:

# netstat -in
Kernel Interface table
Iface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
br0       1500   850276      0   9811 0        138039      0      0      0 BMPRU
eth0      1500   859789      0   1739 0        138070      0      0      0 BMRU
lo       65536     3749      0      0 0          3749      0      0      0 LRU

Which one would you take here? :)

M
Maxim_Q, 2019-03-05
@Maxim_Q

run the code:
now your external IP is in the $icanhazip variable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question