1

So here I tried to get from the ifconfig file, but same with errors with simple ifconfig command

!#/bin/sh
if [/home/pi/ifconfig | grep -Eo ‘inet (addr:)?([0-9]*\.){3}[0-9]*’ | grep -Eo ‘([0-9]*\.){3}[0-9]*’ | grep -v ‘127.0.0.1’ = *.*.1.*]
then
echo “good1”
else
echo “notGood2”
fi

The errors what I got

test: 2: test: [/home/pi/ifconfig: not found
grep: =: No such file or directory
grep: *.*.1.*]: No such file or directory
notGood2
  • 1
    shellcheck.net is a good resource to check for syntax errors in your shell code. Hint [ is a command not just syntax. – glenn jackman Oct 17 '18 at 18:17
2

You can use ip addr to show the IP addresses of all interfaces and subnets on your host:

$ ip -f inet addr show | awk '$1 == "inet" { print $2 }'
127.0.0.1/8
192.168.0.2/24

If you don't care about the subnet, you can strip that out:

$ ip -f inet addr show | awk '$1 == "inet" { print $2 }' | cut -d/ -f1
127.0.0.1
192.168.0.2

Per comment, if you want to see for some reason only what the third octet of your IP address(es) is/are, this is simple enough:

# given this:
$ ip -f inet addr show | awk '$1 == "inet" { print $2 }'
127.0.0.1/8
192.168.25.2/24
# we can do this:
$ ip -f inet addr show | awk '$1 == "inet" { print $2 }' | cut -d. -f3
0
25
  • O can use this like normal command, but how can I use it in shell? My main problem that, I cant check the IPv4 address what number contains on the third position (in shell). – Nous0820 Oct 17 '18 at 18:45
1
#!/bin/bash
for i in $(/sbin/ifconfig | grep inet | awk '{print $2}')
do
    if [[ $i  =~ ^[0-9]{1,3}\.[0-9]{1,3}\.1|0.[0-9]{1,3}$ ]]; then
    echo "$i good1"
    else 
    echo "$i notGood2" 
    fi
done
0

I found the answer guys I will explain the i = 1 because it is

i=1
if [ $i = 1 ]; then
echo $i good1
else
echo $i notGood2
fi

This is what I want Anyway both of you helped to get the right answer guys! Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.