Question

I'm trying to get my local ip with ifconfig and write it to file but for some reason fail to do so.

run:
    LOCALIP=$(shell ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | awk '{print $1}') &
    echo "var LOCAL_IP = '${LOCALIP}'" > local_ip.js &

It does get the correct IP but for some reason fails to write it to file and file contains only var LOCAL_IP = ''

Could anyone help me and tell what I'm doing wrong?

Was it helpful?

Solution

Two issues: one, each separate command in a Makefile recipe is executed in a separate shell, so you need to "merge" them. Two, you need to double the $ in the echo so that it is sent to the shell, not expanded first by make. This should work:

run:
        LOCALIP=$(shell ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | awk '{print $1}'); \
        echo "var LOCAL_IP = '$${LOCALIP}'" > local_ip.js

The semicolon and the line-continuation backslash ensure that the entire recipe is executed in the same shell, so that LOCALIP is still set when the echo is run. You could "simplify" this by embedding the command substitution directly in the argument to echo.

run:
        echo "var LOCAL_IP = '$(shell ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | awk '{print $1}')'" > local_ip.js

OTHER TIPS

This awk can work:

ifconfig | awk -F: '/inet addr/&& !($2 ~ /127\.0\.0\.1/){gsub(/ .*/, "", $2); print $2}'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top