3

I don't how to use regex properly in bash, i got an error trying to do in this way, what is wrong in that regex verification?

#!/bin/bash

if [ ! $# -eq 1 ]; then
        echo "Error: wrong parameters"
else
        if [ $1 =~ "[a-z]" ]; then
                echo "$1: word"
        elif [ $1 =~ "[0-9]" ]; then
                echo "$1: number"
        else
                echo "$1: invalid parameter"
        fi
fi
1
  • For a simple check like this, consider case. case $1 in *[!A-Za-z0-9]*) echo invalid;; *[A-za-z]*) echo word;; '') echo empty;; *) echo number;; esac Commented Mar 1, 2012 at 15:36

3 Answers 3

15

I have reworked your script and get the expected result with the following:

  #!/bin/bash                                                                                                                                                                                      
  if [ ! $# -eq 1 ]; then
    echo "Error: wrong parameters"
  else
    if [[ $1 =~ ^[a-z]+$ ]]; then
      echo "$1: word"
    elif [[ $1 =~ ^[0-9]+$ ]]; then
      echo "$1: number"
    else
      echo "$1: invalid parameter"
    fi
  fi

You do not need to quote your Regex.

Sign up to request clarification or add additional context in comments.

1 Comment

More than that, you should not quote the regex: from the manpage, "Any part of the pattern may be quoted to force it to be matched as a string"
6

Don't quote the regex, and use double brackets:

[[ "$1" =~ [a-z] ]]

It's not strictly necessary to quote the variable in this specific case, but it doesn't hurt and it's good practice to always quote strings which contain variables because of the very, very numerous pitfalls related to word splitting.

2 Comments

Thanks l0b0, that works, can you explain why the two brackets?
The double brackets indicate the bash-specific conditional construct that implements the regex matching operator =~
-1

Use two brackets :

if [[ "$1" =~ [a-z] ]] ; then

3 Comments

i still get "invalid parameter"
The pattern merely checks that there is one alphabetic character, not that there are no non-alphabetics. Other answers have already provided a complete solution.
@tripleee the question asked for the proper mechanism to use reg-ex in bash, not for correctness in a regex pattern to match "words" (although I now see that was what in fact Ramon was trying to do)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.