Search code examples
regexbashif-statementsh

bash regex in if statement


I'm trying to add name-checking with regular expression, that passes only characters and digits but no special symbols given from the output. I wrote this code, but it's does not working. It shows "not ok" either when I'm typing only characters with digits or chars+special symbols

#!/bin/bash
regex="/^[a-zA-Z0-9_]+$/gm"
read -p "Type smth: " text

if [[ $text =~ $regex ]]
then
    echo "ok"
else
    echo "not ok"
fi

Here's the output:

user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello$#!
not ok

user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello
not ok

Solution

  • You can use

    if [[ $text =~ ^[[:alnum:]_]+$ ]]
    then
        echo "ok"
    else
        echo "not ok"
    fi
    

    Details:

    • ^ - start of string
    • [[:alnum:]_]+ - one or more letters, digits or underscores
    • $ - end of string.

    Note the absence of regex delimiter chars.

    See the online demo.