REGEX for a Full_PATH/Command --with-options


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting REGEX for a Full_PATH/Command --with-options
# 1  
Old 10-19-2012
REGEX for a Full_PATH/Command --with-options

Hello All,

I'm trying to match some user input.
The User input will be a FULL Path, a Command/Script Name, and any options they choose...

I was able to get this to Match somewhat but I want to be able to print an Error if, for example, the user enters a trailing "/"
after the Command_name and before any Options/Arguments.

What I have so far will Match BOTH of these example:
Code:
# Example 1:
/usr/local/user_dir/bin/my_script -w 10 -c 50

# Example 2: *notice the trailing "/" after "my_script"...
/usr/local/user_dir/bin/my_script/ -w 10 -c 50

The Uncommented Pattern Below matches both of the above examples...
Here is a Couple of the REGEXs I've tried so far:
Code:
user_cmd="$1"

### The 1st Pattern here seems to match only the END of the Command (i.e. It Matches --> "/my_script -w 10 -c 50"
#COMMAND_PATTERN="((/){1,1}([[:alnum:]-_])+) .*"

COMMAND_PATTERN="((/[[:alnum:]_-]*)+).*$"

if [[ "$user_cmd" =~ $COMMAND_PATTERN ]]
 then
    echo "Command is Good"
else
    echo "Error: Command is Wrong"
fi

I think I'm pretty close to getting this but I just can't figure out what I'm missing to have it NOT match:
"/Path/to/Command_name/ -w -c --verbose"
Because of the trailing "/"...?


If anyone has any thoughts please feel free to respond.
Also, I'd really like to keep the Grouping "(..)", because I may use this REGEX as part of another REGEX later on.


Thanks in Advance,
Matt
# 2  
Old 10-19-2012
What exactly are you trying to do here? I foresee problems. What if the user wants to input /usr/local/user_dir/bin/my_script -w "parameter with spaces" ?

Storing every possible option inside one variable to badly split later may not be the way to go. Trying to do everything in one big giant regex doesn't sit well either.

What's your system? What's your shell?

Last edited by Corona688; 10-19-2012 at 02:47 PM..
# 3  
Old 10-19-2012
I'm with corona - you are on a long evil path to loads of problems. Do not over look the power of getopts and case statements. getopts is POSIX, so if you are using a modern shell like ksh or bash it will work for you.
# 4  
Old 10-19-2012
Code:
PATTERN="[/]([/]+| .*$)"

This User Gave Thanks to shamrock For This Post:
# 5  
Old 10-19-2012
Hey Guys, thanks for your replies...

Corona,
If the Options have whitespace in them that's fine, because at the end of the REGEX PATTERN I have a ".*" which will allow that
As far as what System I'm using, this script will be put on multiple servers. All will have Bash on them, and some are AIX, SLES, openSuSE...

Ok, I hear what your saying....
I didn't give the whole story either, I was trying not to go into too much unnecessary depth but here it is.

Basically, what the user is entering is what will be appended to a config file (if entered correctly) containing definitions
of commands for Nagios' NRPE.


The Syntax for the "Command Definition" is as follows:
Code:
command[check_cmdAlias]=/path/to/the/command --option1 --option2 'etc, etc'

Of the above "definition" all of the folloing is mandatory:
1. The "command" keyword (all lower case)
2. The square brackets with your own unique Alias
3. A single "=" sign
4. Lastly, after the "=", the Full Path and Command (with options if necessary)

After doing tons of testing, and lots of trial and error I came up with the following to check the User's input for errors.
It seems to work pretty well after testing with a bunch of different WRONG definitions (on purpose), and it seems to
be pretty accurate in terms of telling the User "Hey, 'this part' of the Command Definition is incorrect..."


What I do after checking the $new_command against the $COMMAND_PATTERN, I break the PATTERN into it's
separate groups.
So there will be 4 different grouping patterns to find, i.e. one for each of the ones listed above...

Then I set each "grouping" PATTERN to its own variable and use them to make an "if/elif/else" statement. So as it goes
through the if statement whichever 'if' returns true, then that part of the command definition is incorrect and I
print an Error and tell the user which part of their command is incorrect and how to fix it...

Something Like This:
For some reason I can't seem to find my most up-to-date REGEX PATTERN... Dam it, I've tried some many different
combinations I've lost track! But You'll get the jist of what I'm doing...
Code:
 # The User's Input is saved in "$new_command"

COMMAND_PATTERN="^(command)(\[{1,1}[[:alnum:]_-\ ]*\]{1,1})(={1,1})((/[[:alnum:]_-]*)+) .*$"

 # Check the User's new Command...
if [[ "$new_command" =~ $COMMAND_PATTERN ]]
  then
        COMMAND_PATTERN_MATCH=0
else
        COMMAND_PATTERN_MATCH=1
fi

 ### Check if the $new_command matched correctly
if [ $COMMAND_PATTERN_MATCH == 0 ]
 then
   # IF THE PATTERN IS CORRECT DO STUFF WITH IT HERE...
         ....MORE CODE....
else
   ### Call Function "bad_commandFormat()":
    #   This function will locate the problem in the New Check Command's Definition
    bad_commandFormat
fi

And this is the If Statement I mentioned above, which is inside the Function "bad_commandFormat()". This will
tell the user which part was wrong, so they don't have to guess where it was...

Code:
bad_commandFormat()
{
    ### Here I break up the COMMAND_PATTERN into 4 separate groups, incrementally adding the next group to the previous as it goes
    START_PATTERN="^(command)"
    ALIAS_PATTERN="^(command)(\[{1,1}[[:alnum:]_-\ ]*\]{1,1})"
    EQUALS_PATTERN="^(command)(\[{1,1}[[:alnum:]_-\ ]*\]{1,1})(={1,1})"
    PATH_PATTERN="^(command)(\[{1,1}[[:alnum:]_-\ ]*\]{1,1})(={1,1})((/[[:alnum:]_-]*)+) .*$"


      ### START Pattern: Begins with "command"
    if [[ ! "$new_command" =~ $START_PATTERN  ]]
     then
        format_ErrString="Your NEW Check_Command does NOT begin with the ${BOLD}\"command\"${OFF} keyword (*must be in ALL lower-case).\n"
        FORMAT_ERR="#1"

      ### ALIAS Pattern: String in-between "[...]" and after "command"
    elif [[ ! "$new_command" =~ $ALIAS_PATTERN  ]]
     then
        FORMAT_ERR="#2"
        format_ErrString="Your NEW Check_Command's ${BOLD}\"Alias\"${OFF} is not formatted correctly.\n"

      ### EQUAL Pattern: Check for equal sign after the alias pattern "command[...]="
    elif [[ ! "$new_command" =~ $EQUALS_PATTERN  ]]
     then
        FORMAT_ERR="#3"
        format_ErrString="A single ${BOLD}Equals Sign → \"=\"${OFF} should immediately follow your Check_Command's Alias.\n"

      ### PATH Pattern: Check for a path to a script after the "="
    elif [[ ! "$new_command" =~ $PATH_PATTERN  ]]
     then
        FORMAT_ERR="#4 and #5"
        format_ErrString="Your NEW Check_Command is missing an ${BOLD}Absolute Path${OFF} to the location of the NEW Check Command.\n"

      ### UNKNOWN: There was an error but we're not sure what the problem is...
    else
        format_ErrString="Found an Unknown Error for your NEW Check_Command. Please compare your command\n                with the example below and try again.\n"
        echo -ne "\tcommand[check_myAlias]=/usr/local/nagios/libexec/check_users -w 10 -c 15"
    fi
}

So with the above function, as it goes through the If Statement, whichever one returns False, that one will set the String
for the Error and then I print some more stuff later in that function...

I'm getting ready to head home for the day, so when I can find my most recent REGEX PATTERN I'll post back with that...
Sorry, today has been a long day.... And my head is sort of spinning right now. SmilieSmilie


Thanks Again,
Matt
# 6  
Old 10-22-2012
Hey Guys, I'm back...

So I decided to start the PATTERN all over from scratch, and I think I got it this time!! Smilie

Here's an example of a CORRECT User Input: (*anything in red is mandatory symbols/keywords)
Code:
command[check_unixUsers]=/usr/local/nagios/libexec/check_users -w 10 -c 20

Here's my NEW $COMMAND_PATTERN:
Code:
COMMAND_PATTERN="^(command)(\[{1,1})([[:alnum:]_\ -]*)(\]{1,1})(={1,1})((/[[:alnum:]_\-]+))+\ .*$"

This NEW REGEX fixes a few things from what my Original Pattern was lacking.

For example, my original pattern would allow for a double square bracket (i.e. "[[" or "]]") before and after the Alias, but now
it will NOT pass if it finds these. Also, I was able to figure out what I was doing wrong in order to have the Pattern
fail if the "absolute path/command_name" ended with a forward slash --> "/"...

For the Problem I was having in my OP (i.e. "/Absolute/Path/to/Command_Name/ -w 5 -c 10" ending with a " / " )
I think the problem was that at the end of that group for the "absolute path", I had ended it with an " * " when I should
have ended it with a "+"... When I had it end with a *, it was saying, match a "/" (forward slash), then match 0 or more
"letters/numers/-/_" so if the command name had ended with a "/", then it would pass because there WAS 0 or more
"letter/numbers..." after the last "/" so it would return TRUE

I changed the end of the PATTERN to this (below) and it seems to work much better now!
Code:
## This Pattern will match any letter "A-z" any number "0-9", a "-", and a "_", all starting with a "/".
# Example Matching Pattern -->   "/usr" 
#   Using the Grouping method below combined with the "+" will say match one or more groups like these below:
#        "/usr"   "/my_dir"    "/my-dir"    "/dir_num1"    etc....
# *So if it finds a group like this --> "/usr/myCommand/ -w..."   it will fail!

 ((/[[:alnum:]_\-]+))+\ .*$

Thanks again for all your replies and suggestions! Much Appreciated!


Thanks Again,
Matt
# 7  
Old 10-22-2012
Quote:
Originally Posted by mrm5102
Hey Guys, thanks for your replies...

Corona,
If the Options have whitespace in them that's fine, because at the end of the REGEX PATTERN I have a ".*" which will allow that
No, it's not. You won't actually be able to use those options later, stored that way, because the shell will split on all whitespace, not just the "right" whitespace.

You are going to hit walls with this plan, soon.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Sendmail K command regex: adding exclusion/negative lookahead to regex -a@MATCH

I'm trying to get some exclusions into our sendmail regular expression for the K command. The following configuration & regex works: LOCAL_CONFIG # Kcheckaddress regex -a@MATCH +<@+?\.++?\.(us|info|to|br|bid|cn|ru) LOCAL_RULESETS SLocal_check_mail # check address against various regex... (0 Replies)
Discussion started by: RobbieTheK
0 Replies

2. UNIX for Beginners Questions & Answers

Ls command options

Hi, If I want to list files with names containing a certain letter like " a " using just one ls command, is there any way of doing that? Note that it is containing a letter instead of one of the following (starting, ending with a letter or having the letter in between). what I want is to show... (1 Reply)
Discussion started by: AAAnni
1 Replies

3. Shell Programming and Scripting

Help executing command with options

Hi, I have this command in a shell script and I can get it to echo ok, but when I try to execute the command I get a "file not found" error. Which is strange because, if I copy and paste the same command at the cli it works ok. What am I doing wrong please? (16 Replies)
Discussion started by: bbbngowc
16 Replies

4. Shell Programming and Scripting

Reading command options one by one

Hi, Just some questions on the script below...? Given: bash-2.03$ command -a option1 name1 name2 ParseOptions() { local Len=${#@} local Ctr=2 #always start at 2 local Name=() local Iter=0 while ; do if <- Is this correct? so I can get the $2... (2 Replies)
Discussion started by: h0ujun
2 Replies

5. UNIX for Dummies Questions & Answers

Override options of rm command

How can i override options of rm command ?? and how can i implement my own options when we delete file using rm commad it will not delete file it has to move some folder....plz suggest some solution. (10 Replies)
Discussion started by: arun508.gatike
10 Replies

6. UNIX for Dummies Questions & Answers

Running set options from the command line and bash command

I'm reading about debugging aids in bash and have come across the set command. It says in my little book that an addition to typing set you can also use them "on the command line when running a script..." and it lists this in a small table: set -o option Command Line... (5 Replies)
Discussion started by: Straitsfan
5 Replies

7. Shell Programming and Scripting

Restricting the ls command options

Hi I want the 'ls' command to display only the file size,date modified and name of the file.What i could see with different options is this: $ls -got packagecount.csv $-rwxrwxrwx 1 393137 Aug 21 14:46 packagecount.csv Now what should be my possible... (4 Replies)
Discussion started by: sushovan
4 Replies

8. HP-UX

Linux - HP UX Command options

Just I gone with the script, I found some command's options which are not compatible with " HP-UX ". If I found any alternate commands to the following, most probably I will solve the issue here. 1. " iostat -x " --> this command's option( x ) is not available in HP-UX... (2 Replies)
Discussion started by: pk_eee
2 Replies

9. Shell Programming and Scripting

how to? launch command with string of command line options

my description from another thread... here's my code: #!/bin/bash IFS=$'\n' function OutputName() { input=$1 echo $input input=`echo "$input" | sed -e 's/.//'` input=`echo "$input".avi` output_name=$input } if ]; then echo... (5 Replies)
Discussion started by: TinCanFury
5 Replies

10. UNIX for Advanced & Expert Users

Split Command options

HI! All iam using Split command to split a large .txt file in to smaller files, The syntax iam using split -25000 Product.txt iam getting four output files but not in .txt format but in some other format , when i checked the properties the Type of the output files is Type can any... (7 Replies)
Discussion started by: mohdtausifsh
7 Replies
Login or Register to Ask a Question