Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash test with double brackets doesn't validate regex correctly

I’m new to the bash scripting world, and during learning I wrote a simple password validator script:

#! /bin/bash

args=("$@")
PASSWORD=${args[1]}
if [[ "$PASSWORD" =~ [0-9A-Za-z] ]]
then
    echo "PASSWORD LEGIT"
else
    echo "WRONG PASSWORD"
    fi

With the argument PassWord12, it should output PASSWORD LEGIT, yet it doesn’t.
I’m using double brackets instead of ‘test’ syntax.
What am I doing wrong?
Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you run declare -p args, you will get declare -a args=([0]="PassWord12") which clearly indicates the value you passed has the 0th index in the array. Positional parameters start at 1, but array indices start at 0.

You may use

args=("$@")
PASSWORD="${args[0]}"
if [[ "$PASSWORD" =~ [0-9A-Za-z] ]]
then
    echo "PASSWORD LEGIT"
else
    echo "WRONG PASSWORD"
fi

If you echo the $PASSWORD, you will see you will see the value passed to the script.

Note that you probably want to use [[:alnum:]] instead of a [0-9A-Za-z].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading