Bash case Statement and Using Line Anchors?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Bash case Statement and Using Line Anchors?
# 1  
Old 08-06-2012
Bash case Statement and Using Line Anchors?

Hello All,

I am writing a script that is to be placed on multiple servers, and of course I've started
running into some compatibility issues for certain shell commands.

The code below worked just fine on most of my machines except for a couple.
Here I had 4 separate lines in my script that checked the format of the user's input. Which
was set to "$new_command" --> i.e. new_command="$1" using the grep command...
Code:
    ### Patterns for checking the NEW Command...
     START_PATTERN="^command"
     ALIAS_PATTERN="^command\[[a-z0-9].*\]"
    EQUALS_PATTERN="^command\[[a-z0-9].*\]="
      PATH_PATTERN="^command\[[A-z0-9].*\]=/[A-z0-9]*/.*"

    ### Grep for new command beginning with the "command" keyword
    echo "$new_command" | grep -ioq "$START_PATTERN"
    GREPSTART_RETCODE=$?

    ### Grep for new command with "command[anyletters/numbers]"
    echo "$new_command" | grep -ioq "$ALIAS_PATTERN"
    GREPALIAS_RETCODE=$?

    ### Grep for new command with a "=" after the alias
    echo "$new_command" | grep -ioq "$EQUALS_PATTERN"
    GREPEQUALS_RETCODE=$?

    ### Grep for new command that has a Absolute Path after the "="
    echo "$new_command" | grep -ioq "$PATH_PATTERN"
    GREPPATH_RETCODE=$?

# ......
### HERE WAS A COUPLE IF STATEMENTS CHECKING ALL THE ABOVE'S RETURN CODES...
# ...... etc ......

Basically it did the grep on the same variable and checked for the specified pattern. Then
below those grep commands there was one if statement for each separate grep command's return code.
Basically they were all just "if [ $GREP***_RETURNCODE != 0 ]", then do some stuff.

But when I tested this on an AIX server in which I installed bash (which is bash version 3.2.16) I am
getting an error with the "grep" command's -o option... Must be an older version of grep (on ksh B.T.W.).

So I wanted to try something other then grep since it doesn't contain the -o option. I thought I would
use bash's "case" statement since it's much cleaner then using a bunch of if/elif/else statements. But
it doesn't seem to recognize the caret "^" symbol...? Is there a way to change this to where it would
recognize it?
Here's my case statement:
Code:
new_command="$1"


case "$new_command" in
       ^command)
            echo "Case 1 = TRUE"
        ;;
        ^command\[[a-z0-9].*\])
            echo "Case 2 = TRUE"
        ;;
        ^command\[[a-z0-9].*\]=)
            echo "Case 3 = TRUE"
        ;;
        ^command\[[A-z0-9].*\]=/[A-z0-9]*/.*)
            echo "Case 4 = TRUE"
        ;;
        *) 
            echo "IN Default Case, NONE ARE TRUE"
        ;;
esac

So is there any kind of shopt I can turn on to change this or does the case statement not have the ability to handle this?

Any thoughts would be great...

Thanks in Advance,
Matt

---------- Post updated at 04:43 PM ---------- Previous update was at 03:59 PM ----------

Hey All,

Yea, so I've been continually search around and I finally came across another forum where someone had a similar question to mine.
Not exactly about using line anchors but other symbols directly related to regex.

The response was that Bash's "case statement" does NOT use Regular Expressions, but uses Globs instead... I was afraid of that...

I guess I'll have to go with a set of if/elif/else statements...

Thanks Anyway,
Matt
# 2  
Old 08-06-2012
You can match most with globs and put extra code within case 4 to trap non-digits between the '/' chars:

Code:
case "command[a_]=/9/rest" in
       command)
            echo "Case 1 = TRUE"
        ;;
        command\[[a-z0-9]*\])
            echo "Case 2 = TRUE"
        ;;
        command\[[a-z0-9]*\]=)
            echo "Case 3 = TRUE"
        ;;
        command\[[A-z0-9]*\]=/*/*)
            # check using grep for bad value inbetween / and /
            echo "Case 4 = TRUE"
        ;;
        *)
            echo "IN Default Case, NONE ARE TRUE"
        ;;
esac

This User Gave Thanks to Chubler_XL For This Post:
# 3  
Old 08-06-2012
bash can work with regex too, though it's generally better to use case for portability.
Code:
#!/bin/bash
re_start='^command'
re_alias='^command\[[[:alnum:]][^]]*\]'
re_equals='^command\[[[:alnum:]][^]]*\]='
re_path='^command\[[[:alnum:]][^]]*\]=/[[:alnum:]]*/.*'


test=$1
if [[ $test =~ $re_path ]]; then
        echo "matches path regex [[${BASH_REMATCH[0]}]]"
elif [[ $test =~ $re_equals ]]; then
        echo "matches equals regex [[${BASH_REMATCH[0]}]"
elif [[ $test =~ $re_alias ]]; then
        echo "matches alias regex [[${BASH_REMATCH[0]}]"
elif [[ $test =~ $re_start ]]; then
        echo "matches start [[${BASH_REMATCH[0]}]"
else
        echo "bugger if i know"
fi

Code:
$ for str in 'command[new]=/path/to/stuff' 'command[abc123]=str' 'command[broke]noequals' 'command!=foobar'; do ./re "$str"; done
matches path regex [[command[new]=/path/to/stuff]]
matches equals regex [[command[abc123]=]
matches alias regex [[command[broke]]
matches start [[command]

This User Gave Thanks to neutronscott For This Post:
# 4  
Old 08-07-2012
Hey Chubler_XL, thanks for the reply.

Yea, that's not a bad idea... Maybe I'll give that a try.


Hey neutronscott, thanks for the reply...

I originally did have this part of the script in If statements, but I was trying to shorten things up a bit and use a case
statement. But it looks like I'm going to go back to the if statements.

Thank you both for your help!


Thanks Again,
Matt
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Bash read input in case statement not working as expected

I'm having an issue with bash read input when using a case statement. The script halts and doesn't read the input on the first loop. if I hit enter then the scripts starts to respond as expected. Need some help here. defaultans=8hrs read -e -i $defaultans -p "${bldwht}How long would you like... (5 Replies)
Discussion started by: woodson2
5 Replies

2. Shell Programming and Scripting

BASH - case statement

Hi Gurus, I have the below BASH code which does not works for upper case alphabets except Z (upper case Z). What may be the reason. Also escape sequences like \n, \t, \b, \033(1m \033(0m (For bold letter) are not working. case $var in ) echo "Lower case alphabet" ;; ... (7 Replies)
Discussion started by: GaneshAnanth
7 Replies

3. Programming

Passing arguments from command line to switch case statement in C

Hi Am pretty new to C.. Am trying to pass the arguments from command line and use them in switch case statement.. i have tried the following #include <stdlib.h> main(int argc, char* argv) { int num=0; if ( argc == 2 ) num = argv; printf("%d is the num value",num); switch ( num ) ... (2 Replies)
Discussion started by: Priya Amaresh
2 Replies

4. Shell Programming and Scripting

Case Statement

Hey, guys I really need some help with a project. "Write a shell program that examines the command line arguments, counts and collects the number of options. Basically it has to collect and count the arguments that start with a "-" and the one's that don't start with a - I know I have to use... (2 Replies)
Discussion started by: sk192010`
2 Replies

5. Shell Programming and Scripting

Problem using bash case statement

I have the following bash script and it is not accepting the lines "--"|"--""-") "--""-"") while do echo "Current Argument is ${1}" case "$1" in "--"|"--""-") echo "Argument is ${1}" shift # Skip ahead one to the next argument. ... (1 Reply)
Discussion started by: kristinu
1 Replies

6. Shell Programming and Scripting

Can you use logical operators in a case statement (bash)?

I'm pretty sure I already know the answer to this, but I want to make sure I'm not overlooking anything. I'm working on a log monitoring script and every 10 lines I want to display a summary of events. The thing is, there are a lot of possible events, that likely won't have happened, so I only want... (0 Replies)
Discussion started by: DeCoTwc
0 Replies

7. Shell Programming and Scripting

bash case statement output help

greetings, I have a script that is taking input like this: a b c d aa bb aaa bbb ccc ddd and formating it to be like this: a b c d aa bb aaa bbb ccc ddd (4 Replies)
Discussion started by: adambot
4 Replies

8. Shell Programming and Scripting

[BASH] recognise new line regex in case statement

Hi, I'm trying to write a routine to parse a file that contains data that will be read into arrays. The file is composed of labels to identify data types and arbitrary lines of data with the usual remarks and empty new lines as is common with config files. The initial pass is built as so:... (3 Replies)
Discussion started by: ASGR
3 Replies

9. Shell Programming and Scripting

case statement

Hi, I am writing case statement to execute some finction, my requirement is once one of the case statement is executed again it has to prompt for the option. for script in `echo "$Script_Selected"` do case $script in 1) getNoOFActUsers ;; 2) moveServerrOORotation ;; ... (2 Replies)
Discussion started by: Satyak
2 Replies

10. UNIX for Dummies Questions & Answers

CASE statement

Hi, I am writing a bash shell script. My script has a few user defined parameters. When the script runs the first thing it does is make sure that these parameters are valid. One of the parameters is called YEAR. A valid input for YEAR can be 1997-2000. One way I have come up with to ensure... (3 Replies)
Discussion started by: msb65
3 Replies
Login or Register to Ask a Question