I am trying to make a bash script that validates 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 entering, for example /Documents
, that it is an existing directory, the operation is the same and it does not validate the expression, it is as if it will not enter the /
.
How could I correctly validate the expression?
To test a regular expression in bash, you must use the y operator
=~
and must be enclosed in double brackets[[ ]]
,Also, to make the script more compatible between versions , you should place the regular expression in single quotes in a variable beforehand. (Thanks @TomFenech)
As for your regular expression you must add an
+
or*
after[a-zA-Z]
since if you don't, it captures a single character and you want to capture all of them. (use*
if the value/
alone is valid)The IF would look like this:
This is a simplified example:
it is not necessary to declare it, it can be direct:
Example:
You can see more about regex at regex101.com
I think you have it backwards. First check if the user has entered the / and if not send the else if. I leave you the modified code. I've tried it and it works for me.