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.
CodePudding user response:
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]
.