I want to check in Bash a Variable, if it contains a IP-Adress, otherwise the Script should exit with an errormessage. For example : The var "10.01.24.10" should pass, the var "hello" not, but the var "hello, my ip is 10.03.24.44" should pass not too. My Idea would to use grep but I dont know how to build the grep command at this point. Any Ideas?
Asked
Active
Viewed 39 times
-2
-
Welcome to Stack Overflow. [SO is a question and answer page for professional and enthusiast programmers](https://stackoverflow.com/tour). Please add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself. – Cyrus Oct 16 '20 at 08:35
-
Thank you. I don't have any ideas to solve the problem, so I can't add code. – madcat Oct 16 '20 at 08:38
-
Then at least tell us what did you search for, and what did you find? – tripleee Oct 16 '20 at 08:42
-
See: [Check for IP validity](https://stackoverflow.com/q/13777387/3776858) – Cyrus Oct 16 '20 at 08:42
1 Answers
0
You can incorporate the grep command in an if statement as below
ip="192.168.240.2"
if grep -Eq '^([0-9]{1,3}\.){3}([0-9]{1,3})' <<< "$ip"
then
echo "PASS"
else
echo "FAIL"
fi
You can also write the conditional statements as:
grep -Eq '^([0-9]{1,3}\.){3}([0-9]{1,3})' <<< "$ip" && echo "PASS" || echo "FAIL"
This uses && to signify success and || to signify failure

tripleee
- 175,061
- 34
- 275
- 318

Raman Sailopal
- 12,320
- 2
- 11
- 18
-
`#!/bin/bash ip="192.168.240" if grep -Eq '^([0-9]{1,3}.){3}([0-9]{1,3})' <<< $ip then echo "PASS" else echo "FAIL" fi ~ ` If i run this, the script pass too, can i avoid this? – madcat Oct 16 '20 at 08:51
-
The author of this answer forgot to escape the dot `\.`; I have updated to fix this. – tripleee Oct 16 '20 at 08:56