Results 1 to 4 of 4
I am curious if it is possible to compare a variable to a regular expression in an If statement in a shell script? The purpose of this is to validate ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 03-20-2006 #1Just Joined!
- Join Date
- Mar 2006
- Posts
- 1
If condition question
I am curious if it is possible to compare a variable to a regular expression in an If statement in a shell script? The purpose of this is to validate MAC addresses for a script that I am writing. Below is an example of the script that I am trying to work on. I believe this can be accomplished using Perl, but I don't have experience using Perl.
#!/bin/sh
usage ()
{
echo $1
exit -1
}
if [ "$1" = "" ]
then
usage "Usage: $0 <Search Term> <Config File>"
fi
if [ "$1" = "[0-9]" ]
then echo Working MAC Address!
else
echo Not a working MAC address...
fi
#Declare variables
I will probably be making the two if statements into a nested if statement. The second if statment is the one I am having troubles with. It appears that the if statement looks at the expression "[0-9]" as a literal. I know that the [0-9] won't validate MAC addresses, but I was trying to simplify things to figure out why it wasn't working. Any help would be greatly appreciated. Thank you.
- 03-20-2006 #2Linux Newbie
- Join Date
- Oct 2004
- Posts
- 158
try this:
You have to test that the individual numbers are between 0 and 255 alsoCode:if [ `echo "$1" | tr -d '[:digit:]'` = "..." ] ; then echo "sort of kinda good ip address" else echo "bad ip address" fi
- 03-21-2006 #3
I'm relying mostly on Wikipedia for my info on MAC addresses, but it seems that jim's approach won't work because, in the event of three hexadecimals, you can have letters a-f, and in the event of six groups, you can have letters.
I would personally advise use of cut:
You will, of course, need to check how many fields you have somehow, and maybe do an if to determine if you have 3 (all hexadecimals) or 6 (of any grouping).Code:for field in `echo "$1" | cut -d: --output-delimiter=' ' -f 1,2,3,4,5,6`; do if [ << Check to ensure that field is a valid number >> ]; then echo "Good MAC address!!" else echo "Bad MAC address!!" fi done
Good luck!
- 03-24-2006 #4Linux Engineer
- Join Date
- Mar 2005
- Posts
- 1,431
BTW, checking for arguments might be done like this too:
Code:if [ ! "$1" ] then echo Not enough arguments\! exit 1 fi


Reply With Quote
