Home > Net >  How to check ! $ & present in password variable in Shell script
How to check ! $ & present in password variable in Shell script

Time:08-11

I am writing shell script which will validate entered password which should not accept ! $ & sign in password. I need to throw error messages. Kindly help me here.

Here problem occurring when I give password like yt!$&

It is not throwing me error messages

echo "enter password which do not include ! $ & sign" 
read -s password 
if [[ $password != *"&"* || $password != *"!"* || $password != *"$"* ]];
 then 
echo "Do not enter ! $ & in password" else 
echo $password  
fi

CodePudding user response:

x!=a || x!=b || x!=c is equivalent to !(x==a && x==b && x==c).

This is only true when none of the three conditions match.

However, I guess you wish to fail if even a single condition matches.

For that you should use: !(x==a || x==b || x==c).
Or equivalently: x!=a && x!=b && x!=c

After that, it should be clear that you also need to invert the test.


You can combine the tests and shorten to:

if [[ $password == *[\&!$]*  ]]; then 
    echo "Do not enter ! $ & in password"
else 
    echo $password  
fi

(& has to be escaped.)

CodePudding user response:

You can try like that

echo "enter password which do not include ! $ & sign" 
read -s password 
if [[ -n $(echo $password | grep -i '\!\|\&\|\$') ]]; then  
  echo "Do not enter ! $ & in password" 
else    
  echo $password  
fi

Hope It's helpful to you

CodePudding user response:

You just need to fix your condition:

if [[ $password == *"&"* || $password == *"!"* || $password == *"$"* ]]; then
  echo "Do not enter ! $ & in password"
fi
  • Related