How can I create an environment variable that contains the IP address of an adapter that is set via DHCP?
Solution 1
Add the following to /etc/bash.bashrc
The adapter in question is: enp0s3
, so change that accordingly
IP="$(ip addr show enp0s3 | awk '$1 == "inet" { print $2 }' | cut -d/ -f1)"
export SERVER_IP=${IP}
Solution 2
I'm using the following approach:
Suppose that your ethernet name is ens160
:
IP=http://"$(ifconfig ens160 | awk '/inet /{print $2}' | cut -f2 -d':')"
Or:
IP=http://"$(hostname -I | cut -f1 -d' ')"
Test:
echo $IP
http://192.168.100.146
Related videos on Youtube
WhiskerBiscuit
Updated on September 18, 2022Comments
-
WhiskerBiscuit almost 2 years
I am using docker and my scripts reference an environment variable that I'm manually setting in user's foo account /etc/environment like:
SERVER_IP=172.16.16.29
I'm using in my docker-compose file (which I'm running under as foo)
environment: - ServerIP=${SERVER_IP}
I would like to be able to have a variable DHCP_IP that will be populated when adapter enp0s3 has it's IP address set so that I can use DHCP_IP in place of SERVER_IP in the docker-compose above.
I'm not concerned about the IP address changing often as I'm using MAC address filtering in my router to assign the same IP. But I don't want to have to set the IP address manually in a file like I'm doing now.
So how can I put the value of the ip address of enp0s3 into a variable called DHCP_IP, and how can I reference that at the command line or in a file?
Or if you know of an alternative, I'm open to suggestions.
-
goo over 5 years
DHCP_IP="$(ip addr show enp0s3 | grep "inet " | awk '{print $2}' | cut -d/ -f1)"
-
WhiskerBiscuit over 5 yearsI can get the IP already. How do I put it to a variable?
-