Home > Enterprise >  Checking for character in string
Checking for character in string

Time:09-27

I know in Python there's a way to check if there is a certain item in an array or a character in a string and I'm looking for something like this bash.

My script takes a user input (y/n) and uses a while loop to check if input matches either "y" or "n" and this works however I want the script to be non case sensitive meaning I need 4 different checks (YyNa) and I'm sure there's a simpler way to do it.

Something like:

while $var not in "YyNn"

CodePudding user response:

See this thread for an example of validating user input in Bash.

Here is the code modified for your use case:

#!/usr/bin/bash

REGEX='^[YyNn]$'

CHECK="your_user_input_var"

if [[ ! $CHECK =~ $REGEX ]]
then
  echo "Not ok"
else 
  echo "ok"
fi
  •  Tags:  
  • bash
  • Related