Find the answer to your Linux question:
Results 1 to 4 of 4
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Question 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.


    usage ()
    echo $1
    exit -1

    if [ "$1" = "" ]
    usage "Usage: $0 <Search Term> <Config File>"

    if [ "$1" = "[0-9]" ]
    then echo Working MAC Address!
    echo Not a working MAC address...
    #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.

  2. #2
    try this:
    if [ `echo "$1" | tr -d '[:digit:]'` = "..." ] ; then
         echo "sort of kinda good ip address"        
         echo "bad ip address"
    You have to test that the individual numbers are between 0 and 255 also

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Seattle, WA, USA
    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:
    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!!"
            echo "Bad MAC address!!"
    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).

    Good luck!

  4. $spacer_open
  5. #4
    Linux Engineer
    Join Date
    Mar 2005
    BTW, checking for arguments might be done like this too:
    if [ ! "$1" ]
            echo Not enough arguments\!
            exit 1

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts