Regular expressions in Bash

4

I'm trying to make a bash script, validate a directory using regular expressions, what I have is the following.

echo "Ingresa La ruta de tu directorio"
read ruta
if [ $ruta != '^/[a-zA-Z]$' ];then
    echo "No has ingresado una ruta valida, recuerda que la ruta inicia con /"
    echo " "
    continue
else
    if [ -d $ruta ]; then
        echo""
        echo "hey, ya tienes creado tu directorio, tal vez necesites usar otra opcion"
        continue
    fi
fi

When I enter documents, the validation works, but when I enter, for example, /Documents , which is an existing directory, the operation is the same and does not validate the expression, it is as if the / will not be entered.

How could I validate the expression correctly?

    
asked by julian salas 14.02.2016 в 22:21
source

3 answers

6

To check a regular expression in bash, you must use the =~ operator and it must be placed between double brackets [[ ]] ,

Also to make more compatible between versions the script you should place the regular expression in single quotes in a variable previously. (Thanks @TomFenech)

Regarding your regular expression you must add a + or * after [a-zA-Z] because if you do not, capture a single character and you want to capture all of them. (use * if the value% co_of% alone is valid)

The IF would look like this:

regla='^/[a-zA-Z]+$'
if [[ ! $ruta =~ $regla ]]

This is a simplified example:

#!/bin/bash

echo "Ingresa La ruta de tu directorio"
read ruta

regla='^/[a-zA-Z]+$'
if [[ ! $ruta =~ $regla ]]; then
 echo "Tiene la barra"
else
 echo "Falta la barra"
fi
    
answered by 14.02.2016 / 23:45
source
2

it is not necessary to declare it, it can be direct:

if [[ "tu_cadena" =~ "regex" ]]; then

Example:

if [[ "hola" =~ "^[Hh]" ]]; then
    printf "Empieza con h\n"
end

You can see more about regex in regex101.com

    
answered by 20.03.2017 в 07:45
1

I think you've put it backwards. First verify if the user has entered the / and if you do not send the else if. I leave the modified code. I've tried it and it works for me.

    read -p "Ingresa La ruta de tu directorio " ruta

if [ -d $ruta ]
then
     echo " "
     echo "hey, ya tienes creado tu directorio, tal vez necesites usar otra opcion"
     continue
elif [ $ruta != '^/[a-zA-Z]$' ]
then
   echo""
echo "No has ingresado una ruta valida, recuerda que la ruta inicia con /"
                continue
fi
    
answered by 15.02.2016 в 00:11