Ramon Saraiva
Ramon Saraiva

Reputation: 518

Bash parameter verification using regex

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

Upvotes: 3

Views: 11343

Answers (3)

asf107
asf107

Reputation: 1146

Use two brackets :

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

Upvotes: -1

darryn.ten
darryn.ten

Reputation: 6973

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.

Upvotes: 15

l0b0
l0b0

Reputation: 58778

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.

Upvotes: 6

Related Questions